我正在创建一个评分系统,该系统将值四舍五入到最接近的0.5,并包含0到5之间的值。

我如何遍历一个数组,将一个值(四舍五入至最接近的0.5)四舍五入为单位。

let rating = 3.7

let adjustedRating = (Math.round(rating * 2) / 2);

例如3.7:['1','1','1','1',0]

1.4等于['1', '0.5', '0', '0', '0']

let starsToShow = new Array().fill('0'); starsToShow.forEach((v, i) => { ... });

最佳答案

使用Array.from



let rating = 3.7
let adjustedRating = (Math.round(rating * 2) / 2);

console.log(
  Array.from({
    // set array length here
    length: 5
  }, function(_, i) { // iterate over element to update
    // get the difference with index
    var dif = adjustedRating - i;
    // based on the difference assign the array value
    return dif >= 1 ? '1' : dif > 0 ? '0.5' : '0';
  })
);







使用简单的for循环



var rating = 3.7,
  res = [],
  adjustedRating = (Math.round(rating * 2) / 2);

for (var i = 0; i < 5; i++) {
  var dif = adjustedRating - i;
  res.push(dif >= 1 ? '1' : dif > 0 ? '0.5' : '0');
}

console.log(res);

09-19 21:12