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

使用forEach方法为friendsObj添加属性失败,求解决办法

问题分析与解决

需求与现状

需求:使用forEach方法为friendsObj添加属性,以索引为键、名字为属性值,使friendsObj拥有3个属性。

当前代码:

var friendsObj = {};

var friends = ['John', 'Peter', 'Mary'];

friends.forEach(function(name, index) {
  // implement your code below
    console.log('Index '+ index + ' equals ' + name ) ;
});

console.log(friendsObj[0] === 'John');
// -> true
console.log(friendsObj[1] === 'Peter');
// -> true
console.log(friendsObj[2] === 'Mary');
// -> true

运行结果:

Index 0 equals John
Index 1 equals Peter
Index 2 equals Mary
false
false
false
Randomized with seed 51872
Started
F

问题:测试均返回false,friendsObj未正确关联数组元素,无法通过验证。

解决方案

你的代码完全没有对friendsObj进行任何修改操作,只是打印了索引和名字,自然所有测试都会失败。

修改forEach的回调函数,把当前遍历到的名字赋值给friendsObj对应索引的属性即可:

var friendsObj = {};

var friends = ['John', 'Peter', 'Mary'];

friends.forEach(function(name, index) {
  // 给friendsObj添加属性:索引为键,名字为值
  friendsObj[index] = name;
  console.log('Index '+ index + ' equals ' + name ) ;
});

console.log(friendsObj[0] === 'John'); // true
console.log(friendsObj[1] === 'Peter'); // true
console.log(friendsObj[2] === 'Mary'); // true

关键说明

  • forEach的回调函数会接收两个核心参数:当前遍历到的元素(name)和对应的索引(index)
  • 通过friendsObj[index] = name,就能把每个名字以索引为键存入friendsObj
  • 修改完成后,friendsObj会变成{0: 'John', 1: 'Peter', 2: 'Mary'},完全匹配测试要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:25:15