我想知道 JavaScript 中 null
和 undefined
有什么区别。
最佳答案
undefined
表示变量已声明但尚未赋值:
var testVar;
alert(testVar); //shows undefined
alert(typeof testVar); //shows undefined
null
是一个赋值。它可以分配给一个变量作为没有值的表示:
var testVar = null;
alert(testVar); //shows null
alert(typeof testVar); //shows object
从前面的例子中,很明显 undefined
和 null
是两种不同的类型:undefined
是一个类型本身(未定义),而null
是一个对象。
证明:
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
和
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
关于javascript - JavaScript 中的 null 和 undefined 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5076944/