作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要一些帮助来解决需要此操作的问题:
我们需要一个函数 FractionOf 来接收一个数组并返回另一个包含以下三个数字的数组:
in the first position, the fraction of numbers that are positive
in the second position, the fraction of numbers that are zero
in the last position, the fraction of numbers that are negative
例如,FractionOf ([1, 2, 0, -1]) 应返回 [0.5, 0.25, 0.25],假设有 50% 为正值,25% 为零,25% 为负值。
所以我尝试至少以某种形式来回答他们问我的问题,但我坚持如何将百分比转换为分数并将它们添加到位置。
var nums=[1,2,0,0,-1,-4]
function FractionOf(nums){
var result=[]
var num1=0
var num2=0
var num3=0
for(var i=0; i<nums.length; i++){
var num=nums[i]
if(num>0){
num1= num1 + 0.25}
if (num==0){
num2=num2 + 0.25}
if(num<0){
num3=num3 + 0.25}
result.push(num1)
result.push(num2)
result.push(num3)
return result
}
最佳答案
function FractionOf(nums) {
return nums
.reduce((acc, cur) => {
if (cur > 0) acc[0]++;
else if (cur === 0) acc[1]++;
else acc[2]++;
return acc;
}, [0, 0, 0])
.map(result => result / nums.length);
}
此解决方案使用 reduce计算这三种情况的出现次数,从填充 0 的数组开始。结果通过管道传送到map函数,它将每个值除以输入 num
的长度,以获得 0-1 范围内的百分比。
关于javascript - 给定正数、负数和零数数组,返回百分比数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57985964/
我是一名优秀的程序员,十分优秀!