简体   繁体   English

计算数组中每个元素与其他元素的差异百分比

[英]calculate the percentage of difference of each element with others in the array

I have an array const arr = [1,2,3,6,7].我有一个数组 const arr = [1,2,3,6,7]。 I want to calculate the percentage of difference of each element with others in the array.我想计算数组中每个元素与其他元素的差异百分比。 For example: 1 is 100% of arr[0], 50% of arr[1], 33.33% of arr[2], 16.66% of arr[3];例如: 1是arr[0]的100%,arr[1]的50%,arr[2]的33.33%,arr[3]的16.66%; 2 is 200% of arr[0], 100% of arr[1], 66.66% of arr[2], 33.33% of arr[3] etc... Can someone help me solve this problem or at least give a hint? 2是 arr[0] 的 200%、arr[1] 的 100%、arr[2] 的 66.66%、arr[3] 的 33.33% 等等...有人可以帮我解决这个问题或者至少给个提示? I'm very glad your any answers.我很高兴你的任何答案。

I am just practicing my JavaScript so took your project on as a little test.我只是在练习我的 JavaScript,所以把你的项目作为一个小测试。

I have developed a solution below that works.我在下面开发了一个可行的解决方案。 Feel free to ask me questions:)随时问我问题:)

const inputFunc = (num) => {

 const arr = [1,2,3,4,5,6,7]
 let newArr = []
 for(let i = 1; i < arr.length + 1; i++){
  let result = num / i * 100
  if(String(result).length >= 4){
   newArr.push(`${result.toFixed(2)}%`)
  }
  else{
   newArr.push(`${result}%`)
  }
 }
 for(let i = 0; i < newArr.length; i++){
  console.log(newArr[i])
 }
}
inputFunc(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM