我正在嘗試構建一個從陣列中洗掉專案的函式。當我呼叫函式時,陣列和專案都是使用推入的引數配置的。
然而,它沒有回傳預期的 [1,2,4] 而是回傳“還沒有”一個我內置在 if 陳述句中的字串,如果它失敗則回傳。
我可以在控制臺日志中看到 popped 變數 = 3 并且當前的 for 回圈正確地回圈遍歷所有選項。那么為什么它不起作用呢?
const removeFromArray = function() {
let args = Array.from(arguments);
let popped = args.pop();
for (i = 0; i < args.length; i ) {
let current = args[i];
if (current === popped) {
console.log(args);
return args;
} else {
console.log("not yet");
}
}
};
removeFromArray([1, 2, 3, 4], 3);
uj5u.com熱心網友回復:
好的,我已經評論了您的代碼,其中的問題并進行了相應的更改,以便它可以像您希望的那樣作業:
const removeFromArray = function()
{
// arguments is not [1, 2, 3, 4, 3], but instead it's [[1, 2, 3, 4], 3] (length is 2, remember this later)
let args = Array.from(arguments);
// pop works correctly and returns 3
let popped = args.pop();
// here we cannot loop with args.length, as it is 2
// if we change args.length to args[0].length, this will work
for (i = 0; i < args[0].length; i ) {
// args[i] won't work here for the same reason args.length didn't work,
// because we're targeting a wrong thing
// if we change this to args[0][i], it will work
let current = args[0][i];
// After the changes, this if will work correctly
if (current === popped) {
// We can't just return args
// A) we're once again targeting and wrong thing
// B) we haven't removed anything yet
// so lets change this to first splice the array (remove the wanted value)
args[0].splice(i, 1);
// and then return the array where the wanted value is removed
return args[0];
}
}
};
const newArray = removeFromArray([1, 2, 3, 4], 3);
// output the returned new array where 3 is removed
console.log(newArray)
主要問題是它args不包含您認為它所做的(數字陣列),它實際上是args[0]包含的。
另一件事是,當您找到要從陣列中洗掉的值時,您實際上從未將其洗掉。所以這里我們使用 splice 在回傳之前實際洗掉值。
uj5u.com熱心網友回復:
const removeFromArray = function (array, itemToRemove) {
return array.filter(item => item !== itemToRemove);
};
uj5u.com熱心網友回復:
我不知道你為什么不使用任何 JS 的內置函式,比如
let removeFromArray = (arr, remove) => arr.filter(x => x != remove)
let filteredArray = removeFromArray([1, 2, 3, 4], 3)
但讓我們按照你的方式去做
const removeFromArray(arr, remove) {
const items = [];
for (const item of arr) {
if (item != remove) items.push(item)
}
return items;
};
removeFromArray([1, 2, 3, 4], 3);
uj5u.com熱心網友回復:
這就是我的做法,因為你說你想修改原始陣列而不是創建一個新陣列,splice這將是正確的使用工具。
function removeFromArray(arr, rem){
while(~arr.indexOf(rem)){
arr.splice(arr.indexOf(rem), 1);
}
}
var arr = [1, 2, 3, 4, 3];
removeFromArray(arr, 3)
console.log(arr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377714.html
標籤:javascript 数组 循环
上一篇:在Flask中啟動和停止執行緒
