search
HomeWeb Front-endJS TutorialCompilation of common JavaScript error-prone knowledge points

1. Variable scope

var a = 1; 
function test() { 
    var a = 2; 
    console.log(a); // 2 
} 
test();

A is declared and assigned in the function scope above, and it is above the console, so the output a is equal to 2 following the proximity principle.

var a = 1;  
function test2() { 
    console.log(a); // undefined 
    var a = 2; 
} 
test2();

Although a is declared and assigned in the function scope above, it is located under the console, and the a variable is promoted. It has been declared but has not been assigned a value during output, so "undefined" is output.

var a = 1; 
function test3() { 
    console.log(a); // 1 
    a = 2;  
} 
test3();

In the function scope above, a is reassigned, not re-declared, and is located under the console, so a in the global scope is output.

let b = 1; 
function test4() { 
    console.log(b); // b is not defined 
    let b = 2; 
} 
test4();

The ES6 let is used in the function scope above to redeclare the variable b. However, unlike var, let does not have the function of variable promotion, so the output error "b is not defined" is reported.

function test5() { 
    let a = 1; 
    { 
        let a = 2; 
    } 
    console.log(a); // 1 
} 
test5();

The function scope above uses let to declare a as 1, and declares a as 2 in the block-level scope. Because the console is not in the block-level scope within the function, 1 is output.

2. Type comparison

var arr = [], 
    arr2 = [1]; 
console.log(arr === arr2); // false

Compare two different arrays above, console is false.

var arr = [], 
    arr2 = []; 
console.log(arr === arr2); // false

Comparison of the two identical arrays above, because two separate arrays are never equal, so the console is false.

var arr = [], 
    arr2 = {}; 
console.log(typeof(arr) === typeof(arr2)); // true

The above uses typeof to compare arrays and objects. Because typeof obtains NULL, arrays, and objects, the types are all object, so the console is true.

var arr = []; 
console.log(arr instanceof Object); // true 
console.log(arr instanceof Array); // true

The above uses instanceof to determine whether a variable belongs to an instance of an object. Because arrays are also a type of object in JavaScript, both consoles are true.

3.this points to

var obj = { 
    name: 'xiaoming', 
    getName: function () { 
        return this.name 
    } 
}; 
console.log(obj.getName());  // 'xiaoming'

This in the object method above points to the object itself, so "xiaoming" is output.

var obj = { 
    myName: 'xiaoming', 
    getName: function () { 
        return this.myName 
    } 
}; 
var nameFn = obj.getName; 
console.log(nameFn()); // undefined

The method in the object is assigned to a variable above. At this time, this in the method will no longer point to the obj object, but to the window object, so the console is "undefined".

var obj = { 
    myName: 'xiaoming', 
    getName: function () { 
        return this.myName 
    } 
};  
var obj2 = { 
    myName: 'xiaohua'  
}; 
var nameFn = obj.getName; 
console.log(nameFn.apply(obj2)); // 'xiaohua'

The method in the obj object is also assigned to the variable nameFn above, but this is pointed to the obj2 object through the apply method, so the final console is 'xiaohua'.

4. Function parameters

function test6() { 
    console.log(arguments); // [1, 2] 
} 
test6(1, 2);

The above uses the arguments object in the function to obtain the parameter array passed into the function, so the output array is [1, 2].

function test7 () { 
    return function () { 
        console.log(arguments); // 未执行到此,无输出 
    } 
} 
test7(1, 2);

The above also uses arguments to obtain parameters, but because test7(1, 2) does not execute the function in return, there is no output. If test7(1, 2)(3, 4) is executed, [3, 4] will be output .

var args = [1, 2]; 
function test9() { 
    console.log(arguments); // [1, 2, 3, 4] 
} 
Array.prototype.push.call(args, 3, 4); 
test9(...args);

The above uses the Array.prototype.push.call() method to insert 3 and 4 into the args array, and uses the ES6 extension operator (...) to expand the array and pass it to test9, so the console is [1, 2, 3, 4].

5. Closure problem

var elem = document.getElementsByTagName('div'); // 如果页面上有5个div 
for(var i = 0; i < elem.length; i++) { 
    elem[i].onclick = function () { 
        alert(i); // 总是5 
    }; 
}

The above is a very common closure problem. The value that pops up when you click on any div is always 5, because when you trigger the click event, the value of i is already 5. You can use the following method Solution:

var elem = document.getElementsByTagName(&#39;div&#39;); // 如果页面上有5个div 
for(var i = 0; i < elem.length; i++) { 
    (function (w) { 
        elem[w].onclick = function () { 
            alert(w); // 依次为0,1,2,3,4 
        }; 
    })(i); 
}

Encapsulate an immediate execution function outside the bound click event and pass i into the function.

6. Object copying and assignment

var obj = { 
    name: &#39;xiaoming&#39;, 
    age: 23 
}; 
 
var newObj = obj; 
newObj.name = &#39;xiaohua&#39;; 
console.log(obj.name); // &#39;xiaohua&#39; 
console.log(newObj.name); // &#39;xiaohua&#39;

Above we assigned the obj object to the newObj object, thus changing the name attribute of newObj, but the name attribute of the obj object was also tampered with. This is because the newObj object actually obtained It's just a memory address, not a real copy, so the obj object is tampered with.

var obj2 = { 
    name: &#39;xiaoming&#39;, 
    age: 23 
}; 
var newObj2 = Object.assign({}, obj2, {color: &#39;blue&#39;}); 
newObj2.name = &#39;xiaohua&#39;; 
console.log(obj2.name); // &#39;xiaoming&#39; 
console.log(newObj2.name); // &#39;xiaohua&#39; 
console.log(newObj2.color); // &#39;blue&#39;

Using the Object.assign() method above to perform a deep copy of the object can avoid the possibility of the source object being tampered with. Because the Object.assign() method can copy any number of the source object's own enumerable properties to the target object, and then return the target object.

var obj3 = { 
    name: &#39;xiaoming&#39;, 
    age: 23 
}; 
var newObj3 = Object.create(obj3); 
newObj3.name = &#39;xiaohua&#39;; 
console.log(obj3.name); // &#39;xiaoming&#39; 
console.log(newObj3.name); // &#39;xiaohua&#39;

We can also use the Object.create() method to copy the object. The Object.create() method can create a new object with the specified prototype object and properties.

Conclusion

Learning JavaScript is a long process and cannot be accomplished overnight. I hope that the points introduced in this article can help students learning JavaScript to have a deeper understanding and mastery of JavaScript syntax and avoid detours.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

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
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)