JavaScript数组转换算法求助:代码逻辑错误排查及方向指引
算法代码问题排查指引
问题背景
给定数组a,需输出同长度数组b,转换规则为:对于每个索引i(0≤i≤a.length-1),b[i] = a[i-1] + a[i] + a[i+1];若求和中的元素不存在,则用0替代(例如b[0] = 0 + a[0] + a[1])。
测试输入[2, 4, 6]时,代码输出[2, 6, 10],但正确结果应为[6, 12, 6],需排查代码问题。
待排查代码
function solution(a) { let b = []; for (let i = 0; i < a.length; i++){ // start the count of each element of the new "b" array at equal to the matching element of original given "a", since that is one of the elements needed to add to each index b[i] = a[i] if (i-1 >= 0){ b[i] += a[i-1] } if (a[i+1] < a.length){ b[i] += a[i+1] } } return b } const array = [2, 4, 6] console.log(solution(array))
错误点与方向指引
- 错误点:判断
a[i+1]是否存在的条件逻辑完全错误。当前代码是拿数组元素的值和数组长度做比较,而非判断**索引i+1**是否处于数组的有效索引范围内。 - 方向指引:重新梳理索引合法性的判断逻辑——数组的有效索引范围是
0到a.length-1,你需要针对i+1这个索引值做范围判断,而非其对应的数组元素值。
内容的提问来源于stack exchange,提问作者user18624774
相关产品推荐
相关产品推荐

