【问题标题】:splice inside a loop doesnt seem to be working循环内的拼接似乎不起作用
【发布时间】:2019-05-24 15:03:38
【问题描述】:

我正在循环到一个 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 个……关于拼接的东西?

【问题讨论】:

  • 您在遍历该数组时从数组中删除值。拼接时,该数组的长度会发生变化。
  • 你在做拼接时更新 i 吗?您应该将 i 减 1,因为索引不再有效

标签: javascript loops splice


【解决方案1】:

来自splice 的数组将重新索引,因此对于最后一项 i 将为 1 并且数组长度也将为 1 它不会进入循环,因此您不会在 for 循环中得到期望的结果。您可以使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多