循环内的拼接似乎不起作用
splice inside a loop doesnt seem to be working
我正在循环到一个 json 对象,其中有一个对象数组。
我想从我的数组中删除在 iban 上具有空值且在帐号上具有超过 12 位数字的对象。
如果这两个条件都满足,我想删除该项目。
我的列表中有 3 项应删除,因为它们符合此条件,但只有 2 项被删除。
我的函数是这样的
for (var i = 0; i < benefs.length; i++) {
var befNumberIban = benefs[i].Iban;
var befNumber = benefs[i].AccountNumber;
if (befNumber != null) {
if (isBefLenght && (befNumberIban == null || befNumberIban == "")) {
benefs.splice(i, 1);
我不明白为什么它只删除满足条件的我们的3个对象中的2个...关于拼接的东西?
从 splice the array will re-indexed, so for the last item i will be 1 and array length will be 1 too it will not go inside the loop and hence you are not getting the desire result inside for loop. You can use the filter 轻松实现。
const benefs = [{
Iban: null,
AccountNumber: "",
}, {
Iban: null,
AccountNumber: "",
}, {
Iban: null,
AccountNumber: "",
}]
const isBefLenght = true;
var newArray = benefs.filter(a => {
return isBefLenght && !(a.Iban === null || a.befNumberIban === "");
})
console.log(newArray);
我正在循环到一个 json 对象,其中有一个对象数组。 我想从我的数组中删除在 iban 上具有空值且在帐号上具有超过 12 位数字的对象。 如果这两个条件都满足,我想删除该项目。 我的列表中有 3 项应删除,因为它们符合此条件,但只有 2 项被删除。
我的函数是这样的
for (var i = 0; i < benefs.length; i++) {
var befNumberIban = benefs[i].Iban;
var befNumber = benefs[i].AccountNumber;
if (befNumber != null) {
if (isBefLenght && (befNumberIban == null || befNumberIban == "")) {
benefs.splice(i, 1);
我不明白为什么它只删除满足条件的我们的3个对象中的2个...关于拼接的东西?
从 splice the array will re-indexed, so for the last item i will be 1 and array length will be 1 too it will not go inside the loop and hence you are not getting the desire result inside for loop. You can use the filter 轻松实现。
const benefs = [{
Iban: null,
AccountNumber: "",
}, {
Iban: null,
AccountNumber: "",
}, {
Iban: null,
AccountNumber: "",
}]
const isBefLenght = true;
var newArray = benefs.filter(a => {
return isBefLenght && !(a.Iban === null || a.befNumberIban === "");
})
console.log(newArray);