下面的片段解释了这个问题
//Outside array
console.log(String(undefined)); //undefined
console.log(String(null)); //null
console.log(String(5.55)); //5.55
//inside array
console.log(String([undefined])); // ""
console.log(String([null])); // ""
console.log(String([5.55])); //5.5
为什么 null
和 undefined
在数组内外转换为字符串时表现出不同的行为。
最佳答案
当数组被隐式强制转换为字符串时,它会在数组上调用 .join(,)
:
15.4.4.2 Array.prototype.toString ( )
- Let func be the result of calling the [[Get]] internal method of array with argument "join".
.join
方法特别是将 null 和 undefined 强制转换为空字符串:
15.4.4.5 Array.prototype.join (separator)
- If element0 is undefined or null, let R be the empty String; otherwise, Let R be ToString(element0).
对于 undefined
或 null
以外的值,该元素只会调用 toString
。
换句话说,null
和 undefined
是将元素强制转换为字符串的通常规则的两个特殊异常(exception)。
关于javascript - 将数组转换为字符串时,数组中的 "null"和 "undefined"去哪里了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085386/