代码"new Array(count + 1).join(string)"这是什么意思?它是如何工作的?



我有一个代码可以打印aaaa字符串或计数错误。字符串或计数错误。字符串或计数错误

function repeat_string(string, count) 
{
if ((string == null) || (count < 0) || (count === Infinity) || (count == null))
{
return('Error in string or count.');
}
// Floor count.
return new Array(count + 1).join(string);
}
console.log(repeat_string('a', 4));
console.log(repeat_string('a'));
console.log(repeat_string('a', -2));
console.log(repeat_string('a', Infinity));

但我不明白为什么有4次,即什么会返回新的Array(计数+1(.join(字符串(是吗??

// creates a new array of the specified length,
// filled with undefined
const arr = new Array(3);
// [undefined, undefined, undefined]
// join the elements of the array, using ‘x’ to connect them:
arr.join(‘x’);
// undefined + ‘x’ + undefined + ‘x’ + undefined
// ‘xx’

new Array(count + 1)为您提供一个计数为+1长度的空数组。

CCD_ 2将数组的内容与每个元素之间的CCD_。

在您的情况下,new Array(count + 1).join(string)返回aaaa,因为有5个空格,每个空格之间连接一个"a"。

数组构造函数

Array((构造函数-JavaScript|MDN

语法

新阵列(arrayLength(

arrayLength如果传递给Array构造函数的唯一参数是0和2^32-1(包括0和2^ 32-1(之间的整数,则返回一个新的JavaScript数组,其长度属性设置为该数字(注意:这意味着arrayLength空槽的数组,而不是具有实际未定义值的槽(。如果参数是任何其他数字,则引发RangeError异常

new Array(4)是相同的空数组[,,,,]

联接

Array.prototype.join((-JavaScript | MDN

join((方法通过连接数组(或类似数组的对象(中的所有元素来创建并返回一个新字符串,这些元素由逗号或指定的分隔符字符串分隔。


回应评论的附录

那么,任何其他不超过232的值都会给我范围错误吗??

对不起。因为power是用HTML表示的,所以我没有很好地复制和粘贴power。我把232固定为2^32。

正如@ray-hatfield评论的那样,数组中并不是232。

您可以通过以下操作确认错误:

new Array(Infinity)

VM67:1未捕获的范围错误:无效的数组长度在:1:1

new Array(2**32)

VM337:1未捕获的范围错误:无效的数组长度在:1:1

下面的代码不会产生错误。

new Array(2**32-1)

最新更新