如何遍历数组匹配对象权重值生成目标文本数组?
修正代码实现匹配转换需求
先看看原代码里存在的几个关键问题:
result被声明成了字符串,没法存储多个结果值- 匹配逻辑错误:
answers是纯数值数组,不存在.value属性;而且直接用索引i对应possibleValues[i]完全不对,因为答案的数值和选项数组的索引没有对应关系 - 每次匹配到值时直接覆盖
result,没有把所有结果收集起来 - 循环变量
i没有用var/let/const声明,会意外成为全局变量 - 循环内部的
alert会每次循环都弹出,没法直接查看完整的最终结果
下面是修正后的代码,完美生成你需要的结果数组:
var possibleValues = [ { value1:'Completly Agree', weight:5 }, { value1:'Highly Agree', weight:4 }, { value1:'Partialy Agree', weight:3 }, { value1:'Highly Disagree', weight:2 }, { value1:'Completly Disagree', weight:1 } ]; var answers = [1, 3, 1, 4, 2, 2, 5, 1, 2, 5]; // 把result改成空数组,用来存储所有转换后的文本结果 var result = []; // 遍历answers里的每一个数值答案 for(let i = 0; i < answers.length; i++){ const currentAnswer = answers[i]; // 在possibleValues里精准找到weight和当前答案匹配的选项对象 const matchedOption = possibleValues.find(item => item.weight === currentAnswer); // 确认找到匹配项后,把对应的文本加入结果数组 if(matchedOption){ result.push(matchedOption.value1); } } // 查看最终生成的结果数组 console.log(result); // 输出:['Completly Disagree', 'Partialy Agree', 'Completly Disagree', 'Highly Agree', 'Highly Disagree', 'Highly Disagree', 'Completly Agree', 'Completly Disagree', 'Highly Disagree', 'Completly Agree']
代码改进点说明:
- 将
result改为数组类型,这样才能收集所有转换后的文本结果 - 使用
let声明循环变量i,避免全局变量污染的问题 - 用
Array.find()方法更简洁直观地在选项数组中找到对应权重的选项,替代繁琐的嵌套循环写法 - 每次找到匹配项后,用
push()方法把结果添加到数组末尾,而不是覆盖原有值 - 最后用
console.log输出完整结果,比循环内反复弹出alert更实用
如果你的运行环境不支持ES6的find方法,也可以用兼容的嵌套循环写法:
var possibleValues = [ { value1:'Completly Agree', weight:5 }, { value1:'Highly Agree', weight:4 }, { value1:'Partialy Agree', weight:3 }, { value1:'Highly Disagree', weight:2 }, { value1:'Completly Disagree', weight:1 } ]; var answers = [1, 3, 1, 4, 2, 2, 5, 1, 2, 5]; var result = []; for(var i = 0; i < answers.length; i++){ var currentAnswer = answers[i]; // 嵌套循环遍历选项数组找匹配项 for(var j = 0; j < possibleValues.length; j++){ if(possibleValues[j].weight === currentAnswer){ result.push(possibleValues[j].value1); // 找到匹配后立即跳出内层循环,提升运行效率 break; } } } console.log(result);
内容的提问来源于stack exchange,提问作者Khaukanani Lawrence
相关产品推荐
相关产品推荐

