【问题标题】:array.push() builds array, but array indices are undefindedarray.push() 构建数组,但数组索引未定义
【发布时间】:2020-05-01 16:12:37
【问题描述】:

所以我正在使用一个对象列表来在 JavaScript 中构建一个值数组,但由于某种原因,它正在构建一个带有值的键列表。看来我做得对。

原始数据:

"features" : [
    {
      "attributes" : {
        "vehicle_id" : 2077, 
        "cleaning_time" : 1588198260000
      }, 
      "geometry" : 
      {
        "x" : 0, 
        "y" : 0
      }
    }, 
    {
      "attributes" : {
        "vehicle_id" : 2071, 
        "cleaning_time" : 1588258620000
      }, 
      "geometry" : 
      {
        "x" : 0, 
        "y" : 0
      }
    }, 

构建数组:

let list = [];
for(let item in features){
    let date = new Date(features[item].attributes.cleaning_time)
    if((new Date() - date) < 7200000){
        console.log(features[item].attributes.vehicle_id);
        let veh = features[item].attributes.vehicle_id
        list.push(veh);
    }
}

最终数组:

    []
​
0: 6618
​
1: 2204
​
2: 2204
​
3: 6618
​
4: 2204
​
5: 2204
​
length: 6
​
<prototype>: Array []
app.js:176:11

编辑: 该数据正在加入另一个数据源,下面是用于基于vehicle_id加入的函数。

将列表加入另一个数据源:

for(let i in data){
    let veh = data[i].vehicle.vehicle.id;
    data[i].vehicle.isClean = list.includes(veh);
}

此脚本旨在过滤保留时间少于 2 小时的数据。此脚本每 15 秒运行一次,并且每次都重新评估数据。

【问题讨论】:

  • 不是键,是你在控制台看到的数组的索引
  • 那为什么 list[0] == undefined?
  • 我认为第一行应该是 let features = [ ... 而不仅仅是 "features": [ ... 如果您将其设为可运行的 sn-p 肯定会有所帮助,这样这样的小事被你而不是我们抓住。
  • 输出不是来自您提供的输入。此外,不要让示例依赖于实际日期——这会使它变得不稳定。将new Date() 替换为实际的固定日期。
  • @Wyck 我试图让它告诉我条目是否超过 2 小时。我如何不使用固定时间的 new Date() 。此脚本每 15 秒运行一次。

标签: javascript arrays push


【解决方案1】:

据我所知,您的代码运行正常。根据评论,我调整了代码。

let list = [];
var features = [
    {
      "attributes" : {
        "vehicle_id" : 2077, 
        "cleaning_time" : new Date() - 100
      }, 
      "geometry" : 
      {
        "x" : 0, 
        "y" : 0
      }
    }, 
    {
      "attributes" : {
        "vehicle_id" : 2071, 
        "cleaning_time" : new Date() - 100
      }, 
      "geometry" : 
      {
        "x" : 0, 
        "y" : 0
      }
    }
]
for(let item in features){
    console.log(item)
    let date = new Date(features[item].attributes.cleaning_time)
    console.log(`(new Date() - date) < 7200000 is ${(new Date() - date) < 7200000}`)
    if((new Date() - date) < 7200000){
        console.log(features[item].attributes.vehicle_id);
        let veh = features[item].attributes.vehicle_id
        list.push(veh)
    }
}
console.log(`list[0] == undefined is ${list[0] == undefined}`)

【讨论】:

  • 抱歉,该数据是正在进行的调查的一部分,旨在过滤超过 2 小时前的条目。这 2 个条目是第一次提交的条目,因此它们不会返回 True。我包含的最后一个数组是为了表明它通过了。
  • 你原来的数据结构features[item]undefined。所以list[0] 也是undefined。不是因为.push()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2015-12-15
  • 2011-08-15
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多