javascript - 将数组转换为字符串时,数组中的 "null"和 "undefined"去哪里了?

标签 javascript arrays variables

下面的片段解释了这个问题

//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

为什么 nullundefined 在数组内外转换为字符串时表现出不同的行为。

最佳答案

当数组被隐式强制转换为字符串时,它会在数组上调用 .join(,):

15.4.4.2 Array.prototype.toString ( )

  1. 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)

  1. If element0 is undefined or null, let R be the empty String; otherwise, Let R be ToString(element0).

对于 undefinednull 以外的值,该元素只会调用 toString

换句话说,nullundefined 是将元素强制转换为字符串的通常规则的两个特殊异常(exception)。

关于javascript - 将数组转换为字符串时,数组中的 "null"和 "undefined"去哪里了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085386/

相关文章:

javascript - jQuery .slideUp() 和 .slideDown() 等同于 Angular2

arrays - Swift 按特定顺序加入 2 个数组

java - 使用Next按钮JAVA显示结果集中的每条记录

Java:使用if条件检查char变量的内容

javascript - d3 强制添加和删除节点

javascript - 您可以在 Kendo MVVM View 中编写纯 JavaScript 表达式(与 Knockout 一样)吗?

javascript - 设置后如何将 Express.js 用于新的 Web 应用程序?

c++ - C++ 中固定大小数组的池分配器

powershell - 在Powershell中使用子脚本修改父脚本中的变量

使用浏览器的后处理变量的具有颜色位置的 HTML CSS 渐变