gpt4 book ai didi

javascript - 为什么 [,,].join (' ' ) 长度比数组长度小一?

转载 作者:行者123 更新时间:2023-11-28 17:05:53 25 4
gpt4 key购买 nike

连接 var arr = [,,] 产生的 string 长度背后的原因是什么,如下所示: var str = arr.join( ' ')arr 的长度小 1。

var literal_arr = [,,],
joined_literal_arr = literal_arr.join(' '),
constructor_arr = new Array(2),
joined_constructor_arr = new Array(2).join(' ');

console.log("Literal array notation length = ", literal_arr.length);

console.log("Joined literal array notation string length = ", joined_literal_arr.length);

console.log("Constructor array notation length = ", constructor_arr.length);

console.log("Joined constructor notation string length = ", joined_constructor_arr.length);

最佳答案

根据MDN docs :

If an element is undefined or null, it is converted to the empty string.

在您的情况下,您正在创建一个具有特定长度的数组,没有任何值(它将是未定义)。因此,在加入时会有 length - 1 分隔符(因为 undefined 已被视为空字符串)意味着 length - 1 空格( '')。

关于javascript - 为什么 [,,].join (' ' ) 长度比数组长度小一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com