简体   繁体   English

javascript中数组方法和联接函数的组合输出无法理解

[英]Array method and join function combined output in javascript unable to understand

I defined myArr variable in javascript as follows: 我在javascript定义了myArr变量,如下所示:

var myArr= Array(3);

When I consoled the value of myArr it gave the following output: 当我consoled的值myArr它给了以下的输出:

[undefined × 3]

When I used the javascript join function which is as follows: 当我使用如下的javascript join函数时:

myArr.join('X');

And consoled the output I got the following: consoled输出,我得到以下内容:

"XX"

Can somebody explain me why I got this output? 有人可以解释为什么我得到这个输出吗? I was expecting the output to be 我期望输出是

"undefinedXundefinedX"

Array(3) creates an array of three empty holes . Array(3)创建三个空洞的数组。

To achieve your desired result, you need to fill the holes: Array(3).fill() 为了获得所需的结果,您需要填充孔: Array(3).fill()

Array.prototype.join will perform the string conversions of all array elements and joined into one string. Array.prototype.join将执行所有数组元素的字符串转换,并合并为一个字符串。 If an element is undefined or null, it is converted to the empty string. 如果元素未定义或为null,则将其转换为空字符串。 join 加入

All the undefined elements are equal to ["", "", ""].join('X') 所有未定义的元素都等于[“”,“”,“”] .join('X')

Array(3) will create an array of length 3. Array(3)将创建一个长度为3的数组。

On consoling myArr it will log empty array 安慰myArr ,它将记录空数组

join will join all elements of the array into a string join将把数组的所有元素连接成一个字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM