Whydoesthemodulooperatorreturntrue?
This problem basically says to iterate over an integer, and evaluate if the number is divisible by its left-side number and if it is divisible return a Boolean array.
73312
- 第一个数字没有左边的数字,所以它是假的。
- 下一个是 3/7,计算结果为 false,依此类推。
我运行了测试,一切都很好,但是使用这个数字 (73312),它在应该返回 false 时返回 true。
预期输出 [false,false,true,false,true]
实际产量 [false,false,true,true,true]
function divisibleByLeft(n) {
let flag = false;
const ansArr = [];
const s = JSON.stringify(n);
const arr = [];
for (let i = 0; i < s.length; i++) {
arr.push(parseInt(s[i]));
};
for (let i = 0; i < arr.length; i++) {
let reminder = arr[i] % arr[i - 1];
if (reminder !== 0) {
ansArr.push(flag);
} else {
flag = true;
ansArr.push(flag);
};
};
return ansArr;
};
console.log(divisibleByLeft(73312));
回答
您分配flag给的唯一时间false是在函数的开头。当余数也不为 0 时,要么将其分配给 false:
if (reminder !== 0) {
flag = false;
ansArr.push(flag);
} else {
if (reminder !== 0) {
flag = false;
ansArr.push(flag);
} else {
或者完全放弃它并推送布尔值:
if (reminder !== 0) {
ansArr.push(false);
} else {
或者,更简洁地,将数字映射到一个数字数组,并.map在每次迭代时与数组中的前一个元素进行比较:
- Or ditch it entirely and `ansArr.push(remainder === 0)`