Javascript新的Array和join()方法 [英] Javascript new Array and join() method
问题描述
受到这篇流行演讲的启发,我想找出一些与创建数组有关的问题.假设我正在使用以下方法创建新数组:
Inspired by this popular speech I wanted to figure out some issue related to creating arrays. Let's say I am creating new array with:
Array(3)
在控制台中,我得到:
[未定义,未定义,未定义]
这很明显.假设我正在加入该数组:
Which is pretty obvious. Let's say I am doing joining on that array:
Array(3).join()
作为回应,我得到了:
",,"
这也是可以理解的,因为我想这是三个用逗号分隔的空字符串.但是当我尝试做的时候:
Which is pretty understandable as well, because these are three empty strings, separated by commas, I suppose. But when I am trying to do:
Array(3).join("lorem")
我得到的字符串只有两个重复的"lorem":
I am getting string with only two repeat of "lorem":
"loremlorem"
为什么这个单词有两个而不是三个重复?
Why there are two, not three repeats of that word?
推荐答案
join
使用作为联接程序传递的内容将元素联接在一起.因此,您有三个空字符串环绕" lorem
s:
join
joins the elements together, using what was passed as a joiner. So you have three empty strings "surrounding" the lorem
s:
|lorem|lorem|
如果不使用空数组,可能会更加明显:
It might be a little more obvious if you don't use an empty array:
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
顺便说一句,您的第一个示例 join
输出是不正确的.它应该是,
或,"
.(取决于输出格式.)
And your first example join
output, by the way, is incorrect. It should be ,,
or ",,"
. (Depends on the output format.)
这篇关于Javascript新的Array和join()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!