如何实现从两个数组分别取属性名和值构建返回对象?
代码问题排查与修复
1. 属性名拼写错误(核心问题)
你把数组的长度属性**length拼写成了lenght**,这会导致:
- 条件判断逻辑完全失效:数组没有
lenght属性,访问后得到undefined,所以array1.lenght !== array2.lenght只有当两个数组都没有这个属性时才为false,但后续的array1.lenght === 0永远为false,因此无论数组是否为空、长度是否匹配,都不会触发return null的逻辑。 - 若数组为空,本应返回
null,但现在会继续执行后续代码生成空对象。
2. forEach参数命名不规范
array1.forEach((e1, e2) => { ... })里的第二个参数是索引值,用e2命名容易误解为第二个数组的元素,建议改为index更清晰,避免阅读混淆。
3. 未定义变量引用
console.log(reaction(codes, names))中的codes和names未提前声明定义,执行时会抛出ReferenceError。
修复后的代码
function reaction(array1, array2) { // 修正length拼写,调整条件逻辑(空数组或长度不匹配返回null) if (array1.length !== array2.length || array1.length === 0) { return null; } let obj = {}; // 修正参数命名,明确索引含义 array1.forEach((key, index) => { obj[key] = array2[index]; }); return obj; }; // 示例测试变量 const codes = ['id', 'name', 'age']; const names = [1, 'Alice', 25]; console.log(reaction(codes, names)); // 输出: { id: 1, name: 'Alice', age: 25 }
内容的提问来源于stack exchange,提问作者Ana
相关产品推荐
相关产品推荐

