【问题标题】:For Loop - How to get-assign the index of the last element in an array to the first element as an IDFor循环-如何将数组中最后一个元素的索引作为ID分配给第一个元素
【发布时间】:2020-01-07 20:22:52
【问题描述】:

我正在通过 For 循环构建一个新的对象数组,并且需要为每个新对象分配一个 ID。我需要每个新 Id 成为数组新长度的底部值。

目前的代码是这样的:

var setData = function(data) {

  var newData = [];

  for (var i = 0; i < data.length; i++) {
    if (Util.checkType(data[i].typeId)) {
      newData.push(data[i]);
      data[i].id = i;
    }
  }
  this.data = newData;
};

当前执行的方式导致每个新 Id = 对象在 newData 数组中的索引。我需要与我得到的结果相反。

因此,例如,如果 data.length = 50,并且所有 50 个都通过条件,我需要第一个元素具有“Id”:49,最后一个“Id:0”。

我尝试过向后迭代和跟踪:

  for (var i = data.length - 1; i >= 0; i--)
    if (Util.checkType(data[i].typeId)) {
    data[i].id = i;
    newData.push(data[i]);
      console.log("newData.length", newData.length);
      console.log("data[i].id", data[i].id);
    }
  }
  console.log("newData", newData);
  this.data = newData;

但即使我能看到:

newData.length 1
data[i].id 49

newData.length 2
data[i].id 48

newData.length 3
data[i].id 47 

以此类推,最终 newData 数组中的每个对象仍然有一个 Id = 对象在数组中的索引。

newData = [
  {"address": 123 Main St,
   "duration": some hours or minutes, 
   "Id": 0},
  {"address": 1234 Main St,
   "duration": some hours or minutes, 
   "Id": 1},
   etc..
]

我有什么误解和做错了什么? =(

【问题讨论】:

  • 如果您仅将其设置为 data[i].id,则输出中的 id 是否应该为小写?代码看起来非常简单。什么是 typeId
  • 啊。是的,你是对的。 “id”在我的输出中确实是小写的——我只是输入了上面的内容而不是 copypasta。 typeId 是 Util.checkType 过滤的事件类型。

标签: javascript arrays loops indexing


【解决方案1】:

您可以简单地在 for 循环之前调用第二个变量,并在每次传递时递减它。例如:

var newData = [];

let currId = data.length - 1; // Initialize variable to store the current ID
for (var i = 0; i < data.length; i++)
    if (Util.checkType(data[i].typeId)) {
        data[i].id = currId; // Store the value of currId in the id property of the current object
        newData.push(data[i]);
        console.log("newData.length", newData.length);
        console.log("data[i].id", data[i].id);
        currId--; // Decrement current ID
    }
}
console.log("newData", newData);
this.data = newData;

【讨论】:

    猜你喜欢
    • 2014-02-24
    • 2015-04-18
    • 1970-01-01
    • 2011-09-11
    • 2016-02-22
    • 2021-04-22
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多