数字数组的均等分割 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/11 20:28:17
我们需要编写一个函数,如果我们可以将数组分割成一个元素和其余元素,并且该元素等于除其本身之外的所有其他元素的乘积,则返回 true,否则返回 false。
例如:如果数组为 −
const arr = [1, 56, 2, 4, 7];
则输出应为 true
因为,56 等于 −
2 * 4 * 7 * 1
示例
以下是代码 −
const arr = [1, 56, 2, 4, 7];
const isEqualPartition = arr => {
const creds = arr.reduce((acc, val) => {
let { prod, max } = acc;
if(val > max || !max){
prod *= (max || 1);
max = val;
}else{
prod *= val;
}
return { prod, max };
}, {
prod: 1,
max: null
});
return creds.max === creds.prod;
};
console.log(isEqualPartition(arr));
输出
以下是控制台中的输出 −
true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

