我正在尝试找到我传递给我的函数的任何数字的GCF。 当我提醒我的存储阵列时,我得到的只是0。
为什么我的存储阵列0中唯一的值是?即使循环运行了12次,为什么我的值没有被推入存储阵列?
let gcf = num => {
let storage = [];
for (let i = 0; i <= num; i++) {
// if it divides evenly into num, it is a factor and we want to push it
// into an array
if (i % num == 0) {
storage.push(i);
} else {
continue;
}
}
// will sort the array from highest to lowest
storage = storage.sort((a, b) => {
return b - a;
})
alert(storage[0]);
// and return storage[0] for the gcf
}
gcf(12);
答案 0 :(得分:2)
你的模运算符是向后的;)
let gcf = num => {
let storage = [];
for (let i = 0; i <= num; i++) {
// if it divides evenly into num, it is a factor and we want to push it
// into an array
if (num % i == 0) {
storage.push(i);
} else {
continue;
}
}
// will sort the array from highest to lowest
storage = storage.sort((a, b) => {
return a - b;
})
alert(storage[0]);
// and return storage[0] for the gcf
}
gcf(12);