3 回答

TA貢獻1841條經(jīng)驗 獲得超3個贊
// 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’

TA貢獻1848條經(jīng)驗 獲得超10個贊
new Array(count + 1)
給你一個 count + 1 長度的空數(shù)組。
array.join(string)
將數(shù)組的內(nèi)容與string
每個元素之間的 in 連接起來。
在您的情況下,new Array(count + 1).join(string)
返回 aaaa,因為有 5 個空格,每個空格之間有一個“a”。

TA貢獻1796條經(jīng)驗 獲得超7個贊
數(shù)組構(gòu)造器
Array() 構(gòu)造函數(shù) - JavaScript | MDN
句法
新數(shù)組(數(shù)組長度)
arrayLength 如果傳遞給 Array 構(gòu)造函數(shù)的唯一參數(shù)是 0 到 2^32-1(含)之間的整數(shù),這將返回一個新的 JavaScript 數(shù)組,其 length 屬性設(shè)置為該數(shù)字(注意:這意味著 arrayLength 空槽數(shù)組,而不是具有實際未定義值的插槽)。如果參數(shù)是任何其他數(shù)字,則會拋出 RangeError 異常
new Array(4)
是同一個空數(shù)組[,,,,]
。
加入
Array.prototype.join() - JavaScript | MDN
join() 方法通過連接數(shù)組(或類似數(shù)組的對象)中的所有元素來創(chuàng)建并返回一個新字符串,以逗號或指定的分隔符字符串分隔。
回應(yīng)評論的附錄
那么任何其他不大于 232 的值都會給我范圍錯誤嗎?
對不起。因為權(quán)力是用HTML表達的,所以我沒有很好地復制和粘貼權(quán)力。我將 232 固定為 2^32。
正如@ray hatfield 評論的那樣,遍歷數(shù)組的不是 232 。
您可以通過執(zhí)行以下操作來確認錯誤:
new Array(Infinity)
VM67:1 未捕獲的 RangeError:數(shù)組長度無效:1:1
和
new Array(2**32)
VM337:1 未捕獲的 RangeError:數(shù)組長度無效:1:1
并且下面的代碼不會產(chǎn)生錯誤。
new Array(2**32-1)
添加回答
舉報