1 回答
TA贡献1829条经验 获得超13个赞
原因是外循环从0索引开始。在那一点上,代码不知道它5会在某个时间出现在数组中。
将第一个数字是1条件(w1 + weights[i] === w2 || w2 + weights[i] === w1)是false如此这般嵌套for循环。
如果你把5之前1的代码将返回5
function ScaleBalancing(strArr) {
const w1 = JSON.parse(strArr[0])[0];
const w2 = JSON.parse(strArr[0])[1];
let weights = JSON.parse(strArr[1]);
for (let i = 0; i < weights.length; i++) {
if (w1 + weights[i] === w2 || w2 + weights[i] === w1) {
return '' + weights[i]; // should return 5 and break out of function right?
}
//if this for loop is omitted the function returns 5
for (let j = i + 1; j < weights.length; j++) {
if (w1 + weights[i] + weights[j] === w2 ||
w2 + weights[i] + weights[j] === w1 ||
w1 + weights[i] === w2 + weights[j] ||
w2 + weights[i] === w1 + weights[j]) {
return '' + weights[i] + ',' + weights[j]; //this returns 1,6
}
}
}
return 'not possible';
}
// keep this function call here
console.log(ScaleBalancing(["[6, 1]", "[5, 10, 6, 1]"]));
添加回答
举报