你好 StackOverflow 社區!我叫皮特。
在調查心愛的 Javascript 時,我有點卡住了:
我不確定為什么將 98 個空專案推入我的陣列。
在 Index[0] 和 Index[99] 上,我得到了預期的 IntegerValues。
謝謝您的回答!:)
// create an Array with the size of N(x) and
// fill it with numbers in a range from 0 to 100 randomly.
createNSizedArray = (x) => {
for(let i = 0; i < x; i ) {
var arr = [];
arr[i] = arr.push(Math.round(Math.random()*100));
}
return arr;
}
console.log(createNSizedArray(100));
// output -> [ 31, <98 empty items>, 1 ];
// Why are the other 98 items in the Array empty and how to change them into integer values?
實際上,我檢查了 Items[1-98] 以找出它們的值并檢查它們是否真的為空。
但:
例如,console.log(arr[4]) 將“未定義”回傳給我。所以它們并不是真正的空。
uj5u.com熱心網友回復:
您將獲得一個大部分未定義的陣列,因為您arr在每次迭代時都定義了一個新變數。您應該將宣告移到arr回圈之外。
這是一個快速的替代方案:Array(100).fill().map(_=>Math.round(Math.random()*100))
uj5u.com熱心網友回復:
這是因為您在每次迭代時都創建了一個新陣列。嘗試這個:
createNSizedArray = (x) => {
var arr = [];
for (let i = 0; i < x; i ) {
arr[i] = arr.push(Math.round(Math.random() * 100));
}
return arr;
};
uj5u.com熱心網友回復:
嘗試在 for 回圈之前移動陣列的初始化。這樣可以確保您不會在每次回圈運行時都創建一個新陣列。
uj5u.com熱心網友回復:
您可以使用 Array 方法。
const createNSizeArray = (n) => {
return Array.from({ length: n }, () => Math.round(Math.random()*100 );
};
console.log(createNSizeArray(5)) // [81, 92, 23, 54, 12]
uj5u.com熱心網友回復:
可能的解決方案:
const createNSizedArray = (x) => {
// it had to be moved outside the for-loop to prevent from setting everything so far to an empty array
let arr = [];
for (let i = 0; i < x; i ) {
// here you don't need both arr.push(...) and assignment
arr[i] = Math.round(Math.random()*100);
}
return arr;
}
console.log(createNSizedArray(100));
有什么Array.prototype.push作用:
let arr = [];
console.log(arr);
arr.push(1);
console.log(arr); // [1]
arr.push(2);
console.log(arr); // [1,2]
arr.push(3);
console.log(arr); // [1,2,3]
正如@Vincent 建議的那樣,您想要實作的目標可以很容易地完成:
Array(100).fill().map(_ => Math.round(Math.random() * 100))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453652.html
標籤:javascript 数组 for循环
上一篇:動態更改陣列中的資料
