我循环遍历数组中的元素。如果某个值不在特定范围内,我想删除该元素(该值与之关联)。
这是我到目前为止的内容(参见下面的代码) - 我使用pop方法删除元素,但是数组中的最后一个元素总是被删除而不是if / then中的元素/值声明。我也尝试过拼接方法,但我无法让它工作。关于如何做到这一点的任何想法?
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();
答案 0 :(得分:3)
在迭代数组时从数组中删除元素并不是一个好习惯,相反,您可以使用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);
答案 1 :(得分:1)
为了删除数组的元素,你可以从最后循环并在必要时拼接,因为下一个较小的索引不会受到影响。
function updateLocation() {
var address, p, r = h.length;
while (r--) {
p = h[r][0];
address = h[r][1]; // Get address
if (p >= 21 && p <= 33 && address == hs[r]) {
console.log(address);
} else {
console.log(address + " - OVER 33");
h.splice(r, 1);
console.log(address + " - REMOVED");
}
}
}
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"]],
hs = [["Verbena St"], ["Quitman St"], ["Alan Dr"], ["Newton St"], ["Soth Pl"]];
updateLocation();
console.log(h);