gpt4 book ai didi

javascript - 如果值来自 if/then 语句,则从数组中删除元素 - Javascript

转载 作者:行者123 更新时间:2023-11-30 09:31:18 25 4
gpt4 key购买 nike

我正在遍历数组中的元素。如果某个值不在特定范围内,我想删除该元素(与该值相关联)。

这是我目前所拥有的(见下面的代码)——我正在使用 pop 方法删除元素,但数组中的最后一个元素总是被删除,而不是 if/then 中的元素/值陈述。我也试过 splice 方法,但我无法让它工作。关于如何执行此操作的任何想法?

    var h = [
["29","Verbena St", "500", "2", "2,702"],
["36", "Quitman St", "400", "2", "1,700"],
["32", "Alan Dr", "500", "2", "2,408"],
["34", "Newton St", "300", "2", "1,954"],
["30", "Soth Pl", "400", "2", "1,509"]
];

var hs = [
["Verbena St"],
["Quitman St"],
["Alan Dr"],
["Newton St"],
["Soth Pl"]
];


function Location (){

for (var r = 0; r <= h.length; r++){
var p = h[r][0];
var address = h[r][1]; // Get address
if (p >= 21 && p <= 33 && address == hs[r]){
console.log(address);
}
else {
console.log(address + " - OVER 33");
h.pop(address);
console.log(address + " - REMOVED");
}
}
};

Location();

最佳答案

在遍历数组时从数组中删除元素不是好习惯,相反,您可以使用 filter() 过滤它,如下所示:

var h = [
["29","Verbena St", "500", "2", "2,702"],
["36", "Quitman St", "400", "2", "1,700"],
["32", "Alan Dr", "500", "2", "2,408"],
["34", "Newton St", "300", "2", "1,954"],
["30", "Soth Pl", "400", "2", "1,509"]
];

var hs = [
["Verbena St"],
["Quitman St"],
["Alan Dr"],
["Newton St"],
["Soth Pl"]
];

function Location (){
h = h.filter(function(r, i){ // r = value, i = index
var p=r[0];
var address = r[1]; // Get address
return p >= 21 && p <= 33 && address == hs[i];
});
};

Location();
console.log(h);

或者,如果你想显示消息,你可以使用另一个数组并只将你想要的元素推送到它(最好使用 forEach):

var h = [
["29","Verbena St", "500", "2", "2,702"],
["36", "Quitman St", "400", "2", "1,700"],
["32", "Alan Dr", "500", "2", "2,408"],
["34", "Newton St", "300", "2", "1,954"],
["30", "Soth Pl", "400", "2", "1,509"]
];

var hs = [
["Verbena St"],
["Quitman St"],
["Alan Dr"],
["Newton St"],
["Soth Pl"]
];

function Location (){
var g = [];
h.forEach(function(r, i){ // r = value, i = index
var p = r[0];
var address = r[1]; // Get address
if (p >= 21 && p <= 33 && address == hs[i]){
console.log(address);
g.push(r); // push it
}
else{
console.log(address + " - OVER 33 - REMOVED"); // do nothing
}
});
h = g;
}

Location();
console.log(h);

关于javascript - 如果值来自 if/then 语句,则从数组中删除元素 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com