search
HomeWeb Front-endJS TutorialProblems with JavaScript being easily tricked

Problems with JavaScript being easily tricked

Jun 28, 2020 am 09:50 AM
javascriptfront end

Foreword

Summary: This is the understanding and experience of some JavaScript topics that I have accumulated that I find more interesting or difficult, and will be updated in the long term.

Don’t live your life as a woman. A hundred years of joy and sorrow will come from others.

Text

1.In-depth understanding of setTimeout and setInterval

The author has made a summary in this blog of in-depth understanding of setTimeout and setInterval. We know that JavaScript test orders The products of threads, the two functions use the method of inserting code to achieve pseudo-asynchronous, which is actually the same principle as AJAX. Let’s take a look at this example:

console.log("1");
setTimeout(function(){        
    console.log("3")
},0);    console.log("2");

Result: The console outputs 1, 2, 3 in sequence;

function fn() {
    setTimeout(function(){alert('can you see me?');},1000);
    while(true) {}
}

What do you think the execution result of this code is? The answer is that the alert never appears.
Why is this? Because the while code has not been executed, the code inserted later will never be executed.
To sum up, in fact, JS is a single-threaded product after all. No matter how "asynchronous" it is, it is impossible to break through the single-thread barrier. Therefore, many "asynchronous calls" (including Ajax) are actually just "pseudo-asynchronous". As long as you understand such a concept, it may not be difficult to understand setTimeout and setInterval.

2. Preliminary exploration of closures

We have conducted a preliminary discussion in this blog: A preliminary exploration of closures in JavaScript. There are several topics that I personally find quite interesting:

  var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  alert(object.getNameFunc()());//The Window
   var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };
    }
  };  
  alert(object.getNameFunc()());//My Object
function fun(n,o) {
  console.log(o)
  return {
    fun:function(m){
      return fun(m,n);
    }
  };
}
var a = fun(0);  a.fun(1);  a.fun(2);  a.fun(3);//undefined,?,?,?
var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?
var c = fun(0).fun(1);  c.fun(2);  c.fun(3);//undefined,?,?,?

//Question: What are the outputs of the three lines a, b, and c?

This is a very typical JS closure problem. There are three levels of fun functions nested in it. It is particularly important to figure out which fun function the fun function of each level is.

//Answer:
//a: undefined,0,0,0
//b: undefined,0,1,2
//c : undefined,0,1,1

3. Array/map,Number/parseInt

["1", "2", "3"].map(parseInt)//求输出结果复制代码

First, map accepts two parameters, a callback function callback, and a callback function this value
The callback function accepts three parameters currentValue, index, array; and in the question, map only passes in the callback function--parseInt. Secondly, parseInt only accepts two parameters string, radix (radix). The legal range of radix is ​​2-36. 0 or the default is 10. So this question asks

parseInt('1', 0);parseInt('2', 1);parseInt('3', 2);复制代码

The latter two parameters are illegal. So the answer is: [1, NaN, NaN];

4. 0.1 0.2!=0.3 and 9999999999999999 == 1000000000000000;

According to the language specification, JavaScript uses the "double-precision 64-bit format defined by the IEEE 754 standard" format IEEE 754 values") represents numbers. From this we can draw an interesting conclusion. Unlike other programming languages ​​(such as C and Java), JavaScript does not distinguish between integer values ​​and floating point values. All numbers are represented by floating point values ​​in JavaScript, so when performing numerical operations Pay special attention when doing so. Loss of precision Take a look at the following example:

0.1 + 0.2 = 0.30000000000000004复制代码

In specific implementations, integer values ​​are usually treated as 32-bit integer variables, and in individual implementations (such as some browsers) Stored as a 32-bit integer variable until it is used to perform some operation not supported by 32-bit integers, this is to facilitate bit manipulation. The precision of large integers will not be lost within 2 to the 53rd power, which means that the browser can accurately calculate all numbers within Math.pow(2,53). Decimal precision, when the finite number represented by the binary representation of a decimal decimal is not When it exceeds 52 bits, it can be stored accurately in JavaScript.
Solution: Math.round( (.1 .2)*100)/100;

5. [1

This question will make people mistakenly think that it is 2>1&&2

1true;true1true;3true;false0true;复制代码

Answer: [true,true] The key point of this question is For the understanding of operators, one is the comparison rules of different types of values ​​in javascript. For details, please see js comparison table and javascript equality judgment; the other is the understanding of comparison operators and assignment operators, that is, one from left to right and one from right. Turn to the left~

6. The history of browser confusion (1)

3.toString;3..toString;3...toString;复制代码

This question feels very imaginative~ Let me tell you the answer first: error,'3',error;
But if it is

var a=3;
a.toString;复制代码

but it is legal, the answer is '3';
Why?
Because 1.1, 1.,.1 are all legal numbers in JS! So when parsing 3.toString, is this a number or a method call? The browser is confused and can only throw an error, so I feel that this question is just playing tricks on the browser...

7. Statement improvement

var name = 'World!';
(function () {
    if (typeof name === 'undefined') {
        var name = 'Jack';
        console.log('Goodbye ' + name);
    } else {
        console.log('Hello ' + name);
    }
})();

The answer is What... When the author did it for the first time, I foolishly thought it was Hello, world... In fact, it is not the case. The correct answer is: Goodbye Jack;
Why, the statement is promoted... The above code is equivalent to the following Code:

var name = 'World!';
(function () {
    var name;
    if (typeof name === 'undefined') {
        name = 'Jack';
        console.log('Goodbye ' + name);
    } else {
        console.log('Hello ' + name);
    }
})();

8. 坑爹史(1)

var a = [0];
if ([0]) {
  console.log(a == true);
} else {
  console.log("wut");
}

读者们你们觉得此题答案是什么呢?true?因为[0]被看做Boolean是被认为是true,理所当然的推出来[0]==true,控制台输出true...看似没错,然而并不是这样滴~[0]这个玩意儿在单独使用的时候是被认为是true的,但用作比较的时候它是false...所以正确答案是false;不信的话,F12控制台输出[0]==false;看是不是true......

###9. 坑爹史(2)

1 + - + + + - + 1

这题应该是等同于:(倒着看)

1 + (a)  => 2
a = - (b) => 1
b = + (c) => -1
c = + (d) => -1
d = + (e) => -1
e = + (f) => -1
f = - (g) => -1
g = + 1   => 1

答案是2

10. 坑爹史(3)

function sidEffecting(ary) {
  ary[0] = ary[2];
}
function bar(a,b,c) {
  c = 10
  sidEffecting(arguments);  return a + b + c;
}
bar(1,1,1)

此题涉及ES6语法,实在坑的不行...arguments
首先 The arguments object is an Array-like object corresponding to the arguments passed to a function.也就是说 arguments 是一个 object, c 就是 arguments2, 所以对于 c 的修改就是对 arguments2 的修改.
所以答案是 21.
然而!!!!!!
当函数参数涉及到 any rest parameters, any default parameters or any destructured parameters 的时候, 这个 arguments 就不在是一个 mapped arguments object 了.....请看:

function sidEffecting(ary) {
  ary[0] = ary[2];
}
function bar(a,b,c=3) {
  c = 10
  sidEffecting(arguments);  return a + b + c;
}
bar(1,1,1)

答案是12...
请读者细细体会!!

11. 坑爹史(4)

[,,,].join(", ")
[,,,] => [undefined × 3]

因为javascript 在定义数组的时候允许最后一个元素后跟一个,, 所以这是个长度为三的稀疏数组(这是长度为三, 并没有 0, 1, 2三个属性哦)
答案: ", , "

12. 浏览器懵逼史(2)

var a = {class: "Animal", name: 'Fido'};
a.class

这个题比较流氓.. 因为是浏览器相关, class是个保留字(现在是个关键字了);Fuck!
所以答案不重要, 重要的是自己在取属性名称的时候尽量避免保留字. 如果使用的话请加引号 a['class']

13.一道容易被人轻视的面试题

function Foo() {
    getName = function () { alert (1); };
    return this;
}
Foo.getName = function () { alert (2);};
Foo.prototype.getName = function () { alert (3);};
var getName = function () { alert (4);};
function getName() { alert (5);}

//请写出以下输出结果:
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();

14.闭包小题

for(var i = 0; i <h3 id="函数的隐式转换">15. 函数的隐式转换</h3><pre class="brush:php;toolbar:false">function fn() {
    return 20;
}
console.log(fn + 10); // 输出结果是多少

function fn() {
    return 20;
}

fn.toString = function() {
    return 10;
}

console.log(fn + 10);  // 输出结果是多少?

function fn() {
    return 20;
}

fn.toString = function() {
    return 10;
}

fn.valueOf = function() {
    return 5;
}

console.log(fn + 10); // 输出结果是多少?

16. 函数防抖和函数节流(ES6)

//函数节流
const throttle = (fun, delay) => {
    let last = null;
    return () => {
        const now = + new Date();
        if (now - last > delay) {
            fun();
            last = now;
        }
    }
}
//实例
const throttleExample  = throttle(() => console.log(1), 1000);
//调用
throttleExample();
throttleExample();
throttleExample();
//函数防抖
const debouce = (fun, delay) => {
    let timer = null;
    return () => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fun();
        }, delay);
    }
}
//实例
const debouceExample = debouce(() => console.log(1), 1000);
//调用
debouceExample();
debouceExample();
debouceExample();

推荐教程:《JS教程

The above is the detailed content of Problems with JavaScript being easily tricked. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use