在 JavaScript 中查找满足某些条件的最小数字
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 3:56:17
我们需要编写一个 JavaScript 函数,该函数将数字作为第一个参数(例如 n),将数字数组作为第二个参数。该函数应返回最小的 n 位数字,该数字是数组中指定的所有元素的倍数。
如果不存在这样的 n 位元素,则应返回最小的此类元素。
例如:如果数组为 −
const arr = [12, 4, 5, 10, 9]
对于 n = 2 和 n = 3,
输出
输出应为 −
180
因此,让我们编写该函数的代码 −
示例
其代码为 −
const arr = [12, 4, 5, 10, 9]
const num1 = 2;
const num2 = 3;
const allDivides = (arr, num) => arr.every(el => num % el === 0);
const smallestMultiple = (arr, num) => {
let smallestN = Math.pow(10, (num - 1));
while(!allDivides(arr, smallestN)){
smallestN++;
};
return smallestN;
};
console.log(smallestMultiple(arr, num1));
console.log(smallestMultiple(arr, num2));
输出
控制台中的输出将是 −
180 180
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

