为何给开发者数组添加greeting属性时仅返回最后一项值?
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
forloop runs withi=0, yourforEachiterates over every object in the list and sets theirGreetingto Sofia’s info. - Next,
i=1kicks in, and yourforEachruns again, overwriting all existingGreetingvalues 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

