提问人:Yashvardhan Mathur 提问时间:12/23/2021 最后编辑:jfriend00Yashvardhan Mathur 更新时间:12/23/2021 访问量:144
只有最后一个元素被添加到数组中?
Only the last element is added to the array?
问:
当我向数组添加元素时,只有最后一个元素被添加到数组中?我无法找出关闭中的问题。
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}
答:
0赞
jfriend00
12/23/2021
#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 中的对象是由指针使用的,因此传递一个或返回一个会传递指向对象的指针 - 对象不会被复制。
评论