You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在数组中动态创建独立对象?JS代码问题求助

解决数组中创建独立对象的问题

我懂你想要的效果——生成一个数组,其中每个元素都是独立的对象:每个对象以linked.related[a][b]作为属性名,对应的属性值就是外层循环的a。现在你的代码没能达成目标,问题出在这两个关键点上:

  1. 你复用了同一个obj对象,每次循环只会覆盖它的属性,根本没生成新的独立对象
  2. includes.push(obj[linked.related[a][b]] = a)这行代码,push的是赋值操作的结果(也就是a的数值),而非你想要的完整对象

修正后的代码

let structures = ["to protect you", 'to find you' , "gtg", 'I was sent',"to moon"];
let linked = { construct: [ [ 'I send', 'I sent', 'I was sent', 'I have been sent'], [], ["to moon", "to earth", "to Mars"], [] ], related: [ ['I was sent', 'I was forced'], ['to protect you', 'to protect us', 'to protect me'], [ "gtg"], ['to find you', 'to judge you', 'to protect you', "to peneterate you"], ['to protect you','to find you', 'to love you'] ] }
add_zeros();
function add_zeros(){ for (let i = 0; i < linked.related.length; i++) { linked.related[i].unshift(0) } }

// 修正后的核心代码
let includes = [];
for (let a = 0; a < linked.related.length; a++) {
  for (let b = 1; b < linked.related[a].length; b++) {
    if(structures.includes(linked.related[a][b])){
      // 每次满足条件时创建全新的空对象
      const newObj = {};
      // 用方括号语法动态设置属性名与值
      newObj[linked.related[a][b]] = a;
      // 将独立对象推入数组
      includes.push(newObj);
    }
  }
}
console.log(includes)

关键说明

  • 每次符合条件时新建一个空对象,确保数组里的每个元素都是独立的,不会出现属性被覆盖的问题
  • 使用方括号语法设置动态属性名,这是JavaScript中给对象添加动态键名的标准写法
  • 最终推入数组的是完整的新对象,而非属性值

运行这段代码后,你会得到预期的结果:

[
  {'I was sent': 0},
  {'to protect you': 1},
  {'gtg': 2},
  {'to find you': 3},
  {'to protect you': 3},
  {'to protect you': 4},
  {'to find you': 4}
]

内容的提问来源于stack exchange,提问作者Sara Ree

火山引擎 最新活动