簡體   English   中英

javascript-數組鍵和填充

[英]javascript - array keys and fill

我發現js的以下行為有些奇怪,無法找出原因。

讓我們假設以下代碼:

var arrayName = new Array(15);
console.log(arrayName);

這將輸出[undefined,undefined,undefined,...](未定義15次)。

現在,使用以下代碼:

var arrayName = new Array(15).fill();
console.log(arrayName);

由於未提供任何用於填充的參數,因此將輸出(按預期)[未定義,未定義,未定義... ...(未定義15次)。

現在讓我們在數組中添加一個循環(使用for格式,而不是增量格式):

var arrayName = new Array(15);
console.log(arrayName);
for (var i in arrayName) {
    console.log(i);
}

這將什么都不輸出(不是我真正希望的原因-我希望數字從0到14)

現在讓我們使用填充代碼:

var arrayName = new Array(15).fill();
console.log(arrayName);
for (var i in arrayName) {
    console.log(i);
}

這將輸出0、1、2,...,14(兩種情況下我都希望得到)。

那么...為什么有所不同?

我認為索引不是在第一種情況下創建的(但是仍然輸出未定義的元素...為什么?)。 這是語言不一致還是背后的邏輯?

PS將鼠標移到空白框上可以查看內容。

基本上:不要在陣列上使用FOR.IN! http : //ilikekillnerds.com/2015/02/stop-writing-slow-javascript/

for.in是對象。 甚至MDN都聲明了這一點: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

該數組已創建並且具有一些索引,但是由於沒有任何實際數據(未定義),那么為什么會有任何鍵?

 //The difference is in enumerable keys: console.log(Object.keys(new Array(15))); //Produces no keys since no data is allocated console.log(Object.keys(new Array(15).fill())); //Produces 15 keys //What you probably want is to loop through the allocated places in the array, not the keys of it: for(var i = 0; i < new Array(15).length; i++) { console.log(i) } 

為什么是這樣?

您是否嘗試過Object.create

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create

 //Allocating a new object var test = Object.create({}, { p: { value: 42 } }); //Logging object... but where is p? console.log("where is p?",test); //there it is :) console.log("there it is",test.p); //Lets try that again test = Object.create({}, { p: { value: 42, enumerable: true } }); //Logging object... and there is p console.log("All good",test); //New object values are non-enumerable by default. Also on Arrays 

var arrayName = new Array(15);
console.log(arrayName);
for (var i in arrayName) {
    console.log(i);
}

讓我們看看以上情況發生了什么。

var arrayName = new Array(15);

如果傳遞給Array構造函數的唯一參數是0到232 ^ -1(含)之間的整數,這將返回一個新的JavaScript數組,其長度設置為該數字。

這就是您在上述情況下所得到的。 因此,它是一個空數組,長度設置為15。現在,您在in循環中使用了它,它遍歷了可枚舉的屬性,並且在每次迭代時將不同的屬性名稱分配給變量i

console.log(arrayName.propertyIsEnumerable('length'));

這將返回false,因此您沒有可枚舉屬性的數組,並且它是一個空數組。 所以你什么也沒得到。

現在,在第二種情況下,由於您使用了fill(),但是沒有傳遞任何值作為第一個參數,該參數用於填充數組。 由於未傳遞任何值,因此整個數組都充滿了未定義的值,並且定義了數組索引直到數組的長度。 (請參見https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill此處的填充構造函數)

還要注意“數組索引只是具有整數名稱的可枚舉屬性”。

現在,for in循環遍歷數組的index屬性,並打印它們的值,該值顯示0-14。

要了解更多信息, 請訪問https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM