如何解决代码“ new Arraycount + 1.joinstring”是什么意思?如何运作?
我有一个打印的代码 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(count + 1).join(string); 的结果是什么?
解决方法
数组构造器
Array() constructor - JavaScript | MDN
语法
新数组(arrayLength)
arrayLength 如果传递给Array构造函数的唯一参数是0到2 ^ 32-1(包括2和32)之间的整数,则此方法返回一个新的JavaScript数组,其length属性设置为该数字(注意:这意味着一个arrayLength空插槽数组,而不是带有实际未定义值的广告位)。如果参数为其他任何数字,则会引发RangeError异常
bottom
是相同的空数组new Array(4)
。
加入
Array.prototype.join() - JavaScript | MDN
join()方法通过连接数组(或类似数组的对象)中的所有元素(由逗号或指定的分隔符字符串分隔)来创建并返回新字符串。
回应评论的附录
任何其他不大于232的数字都会给我范围误差吗?
对不起。因为功能是用HTML表示的,所以我没有很好地复制和粘贴功能。我将232修复为2 ^ 32。
数组不是整个数组,正如@ray hatfield所说。
您可以通过执行以下操作来确认错误:
[,]
VM67:1未捕获的RangeError:无效的数组长度 在:1:1
和
new Array(Infinity)
VM337:1未捕获的RangeError:无效的数组长度 在:1:1
以下代码不会产生错误。
new Array(2**32)
,
new Array(count + 1)
为您提供了一个具有count + 1个长度的空数组。
array.join(string)
将数组的内容与每个元素之间的string
连接起来。
在您的情况下,new Array(count + 1).join(string)
返回aaaaa,因为有5个空格,每个空格之间有一个'a'。
// 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’
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。