You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何给开发者数组添加greeting属性时仅返回最后一项值?

Why All Greetings Are Using the Last Developer's Info?

Let's break down exactly what's going wrong in your code, step by step:

1. Redundant Nested Loops Cause Mass Overwriting

You’ve wrapped a forEach loop inside a standard for loop—this is the biggest culprit. Here’s the play-by-play:

  • When the outer for loop runs with i=0, your forEach iterates over every object in the list and sets their Greeting to Sofia’s info.
  • Next, i=1 kicks in, and your forEach runs again, overwriting all existing Greeting values with Lukas’s info.
  • By the time the loop finishes, every object ends up with the last entry’s data because you kept overwriting them repeatedly.

2. Unnecessary (and Error-Prone) Reference to list[i]

Inside the forEach callback, you already have direct access to the current developer object (you named it string), but you’re instead pulling data from list[i]. This is redundant, and paired with the nested loops, it’s what makes the overwriting happen across all entries.

3. Minor: Property Name Case Mismatch

You’re setting string.Greeting (with a capital G), but the requirement expects a lowercase greeting property. This won’t break the core logic, but it will make your output fail the expected format.


Fixed Code Options

Option 1: Use forEach correctly (no outer loop needed):

list.forEach(function(dev) {
  dev.greeting = `Hi ${dev.firstName}, what do you like the most about ${dev.language}?`;
});
console.log(list);

Option 2: Use map (preferred if you want to avoid mutating the original array):

const updatedList = list.map(dev => ({
  ...dev,
  greeting: `Hi ${dev.firstName}, what do you like the most about ${dev.language}?`
}));
console.log(updatedList);

Both of these will assign the correct, unique greeting to each developer without overwriting previous entries.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:07:40