Javascript 如何对一个数字数组求和,使数组的和为100

Javascript 如何对一个数字数组求和,使数组的和为100,javascript,Javascript,例如[1,1]-->[50,50]和[1,2]-->[33.33,66.67] 这是我的密码: let total = getTotal(arrayOfNum); let remainder = 100 - total; arrayOfNum.map(n => { let newValue = n + ( (remainder / total ) * n); return newValue || 0; }); 当数组中的所有项目均为0 [0,0,0]-->[0,0,0] 当我期待

例如
[1,1]-->[50,50]
[1,2]-->[33.33,66.67]

这是我的密码:

let total = getTotal(arrayOfNum);
let remainder =  100 - total;
arrayOfNum.map(n => {
  let newValue = n + ( (remainder / total ) * n);
 return newValue || 0;
});
当数组中的所有项目均为
0

[0,0,0]-->[0,0,0]

当我期待类似于
[0,0,0]-->[33.33,33.33,33.33]
的东西时,您能看到这个解决方案吗

const t = [0,2];

const total = arrayOfNum.reduce((r,n)=>r+n);

arrayOfNum
          .map(n=> n/total)
          .map(n=> !isNaN(n) ? n * 100 : 1/arrayOfNum.length * 100 )

您可以检查数组是否包含所有零,然后获取获取部分的长度或部分的总和

函数getParts(数组){
var sum=array.reduce((s,v)=>s+v,0);
回报金额
?array.map(v=>100*v/和)
:array.map((u,uu,a)=>100/a.length);
}
console.log([[0,0],[1,1],[1,2,3],[0,0,1]].map(getParts))

作为控制台包装{max height:100%!important;top:0;}
您认为返回值
return newValue | 0正在运行吗?说真的,这段代码一点作用都没有,所以我怀疑它只是在某些情况下不起作用。。。它完全不做任何事
var比率=总长度/长度;array.map(x=>ratio*x)
您希望
[0,0,1]
得到什么结果?所以,唯一的特例是-如果所有项都是0,对吗?为什么您希望
[0,0,0]-->[33.33,33.33,33.33]