JavaScript中的冷知识(持续更新中……)

xiaoxiao2021-02-28  124

本文将记录一些JavaScript中容易出错的点,由于本人知识有限,所以文章将采取持续更新的方式。本文的JavaScript会涉及浏览器端和服务器端的Node.js。可能有点混杂,等文章丰富了再整理吧。您也可以补充一些自己容易犯的错误。如有错误,请不吝指正。

JavaScript = ECMAScript+DOM+BOM

void 0===undefined,实际上void 任何东西都等于undefined

NaN!==NaN,NaN是唯一一个自身和自身不相等的东西

var a=NaN; console.log(a==a)//false console.log(a!==a)//true

isNaN不等同于Number.isNaN()。二者行为是不同的:前者针对所有数据类型,也就是说会对不属于Number类型的参数使用Number转型,而Number.isNaN()方法是ES6新增,只针对Number类型,其他数据类型都会返回false

Number.isNaN(NaN)//true Number.isNaN('NaN')//false isNaN(NaN)//true isNaN('NaN')//true

eval虽然是全局方法,但不等同于window.eval

var color='red'; function test(){ var color='blue'; eval('console.log(color)'); window.eval('console.log(color)'); with(window){ eval('console.log(color)'); } } test() //outputs: //blue //red //red

在全局作用域下使用var和不使用var定义变量是有差别的:前者的[[Configurable]]值为false,这意味着不能使用delete删除,就算又重新被window.variable赋值,仍然不能被删除;而后者等同于直接在window上定义属性。可以被删除。

var color='red'; window.color//red window.color='blue' color//blue delete window.color//false other=1//等同于window.other=1 window.other//1 delete other//true 等同与delete window.other

JSON不支持undefined

parseInt()的第二个参数表示转换时使用的基数,也就是按多少进制解析数据,其有效取值范围为2-36(数字0-9和字母a-z共36个字符可用),不设置或设为0会按10进制处理。设置的数不在这个界限会返回NaN。而toString()的传递参数的范围在2 -36之间,传入其他参数会报错。

parseInt(100,0) //100 parseInt(100,-5) //NaN parseInt(100,36) //1296 parseInt(100,37) //NaN (1293).toString(36) //"zx" (1296).toString(0) //Uncaught RangeError: toString() radix argument must be between 2 and 36(…)

JavaScript中的最小数>0

Number.MAX_VALUE<Infinity //true Number.MIN_VALUE //5e-324 Number.MIN_VALUE>0 //true Number.MIN_SAFE_INTEGER //-9007199254740991 Number.MIN_SAFE_INTEGER<0 //true Number.POSITIVE_INFINITY==Infinity //true Number.NEGATIVE_INFINITY==-Infinity //true

Function构造函数不会形成闭包

function test(){ var color='red'; var f=new Function('console.log(color)') f() } test() //Uncaught ReferenceError: color is not defined function test(){ var color='red'; var f=function(){console.log(color)} f() } test()//red
转载请注明原文地址: https://www.6miu.com/read-58467.html

最新回复(0)