【问题标题】:Only the last element is added to the array?只有最后一个元素被添加到数组中?
【发布时间】:2022-01-23 23:04:39
【问题描述】:

当我向数组添加元素时,只有最后一个元素被添加到数组中?我无法找出关闭中有什么问题。

const data = require('../content/data')

function randomize() {
    const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
    let name_index = 0
    let origin_city_index = 0
    let destination_city_index = 0
    let org_message = {
      name: '',
      origin: '',
      destination: ''
    }
    let ds = [];
    return function getDs() {
      for(let i = 0; i< ds_size; i++) {
        name_index = Math.floor(Math.random() * data.names.length)
        origin_city_index = Math.floor(Math.random() * data.cities.length)
        destination_city_index = Math.floor(Math.random() * data.cities.length)
        org_message.name = data.names[name_index]
        org_message.origin = data.cities[origin_city_index]
        org_message.destination = data.destination[destination_city_index]
        ds.push(org_message)
      }
      return ds
    }
}

module.exports = {randomize}

【问题讨论】:

    标签: javascript node.js closures


    【解决方案1】:

    您正在为数组中的每个条目重复使用相同的 org_message 对象,因此所有数组元素都将指向完全相同的对象(无论您上次修改了该对象),因此都将包含完全相同的内容。

    相反,为循环的每次迭代创建一个新对象,以便数组的每个元素都包含自己的对象。在 Javascript 中,对象被传递给函数,从函数返回或作为指针插入数组,而不是副本。因此,ds.push(org_message) 只是将指向 org_message 的指针推入数组,因此如果您希望数组的每个元素都不同,则必须为它们创建一个新对象。


    const data = require('../content/data')
    
    function randomize() {
        const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
        let name_index = 0
        let origin_city_index = 0
        let destination_city_index = 0
        return function getDs() {
          let ds = [];
          for(let i = 0; i< ds_size; i++) {
            let org_message = {
              name: '',
              origin: '',
              destination: ''
            };
            name_index = Math.floor(Math.random() * data.names.length)
            origin_city_index = Math.floor(Math.random() * data.cities.length)
            destination_city_index = Math.floor(Math.random() * data.cities.length)
            org_message.name = data.names[name_index]
            org_message.origin = data.cities[origin_city_index]
            org_message.destination = data.destination[destination_city_index]
            ds.push(org_message)
          }
          return ds
        }
    }
    
    module.exports = {randomize}
    

    我还将ds 的声明移到返回的函数中,因为没有它,您将在每次调用返回的函数时重用相同的ds 数组,这只会在相同的末尾添加更多元素数组,它将修改之前调用返回的数组。

    请记住,Javascript 中的对象是由指针使用的,因此传递一个或返回一个会传递一个指向对象的指针 - 不会复制对象。

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2013-08-05
      • 1970-01-01
      • 2022-12-10
      • 2020-04-14
      • 2017-06-28
      相关资源
      最近更新 更多