Javascript new Array和join()方法

use*_*810 5 javascript

受到这个流行演讲的启发,我想弄清楚与创建数组相关的一些问题.假设我正在创建新数组:

Array(3)

在控制台我得到:

[undefined, undefined, undefined]

这很明显.假设我正在加入该阵列:

Array(3).join()

作为回应我得到:

",,"

这也是可以理解的,因为这些是三个空字符串,用逗号分隔,我想.但是当我想要做的时候:

Array(3).join("lorem")

我得到的字符串只有两个重复的"lorem":

"loremlorem"

为什么有两个,而不是三个重复的那个词?

Ry-*_*Ry- 8

join使用作为连接器传递的内容将元素连接在一起.所以你有三个空字符串"围绕" lorems:

|lorem|lorem|
Run Code Online (Sandbox Code Playgroud)

如果不使用空数组,可能会更明显一些:

var arr = [1, 2, 3, 4, 5]; // Like Array(5), except not sparse

arr.join('-and-'); // 1-and-2-and-3-and-4-and-5
Run Code Online (Sandbox Code Playgroud)

join顺便说一句,你的第一个示例输出是不正确的.它应该是,,",,".(取决于输出格式.)