如何对类别中的数值输入进行分类?

时间:2016-12-26 21:34:34

标签: javascript range classification

我想创建一种优化的方法来对某些标签中的值进行分类。

实施例

输入:12.2,61,77.7 输出:“坏”,“差”,“好”

我创建一个简单的if,但也许存在更好的方式

let output = null;
if (rating <= 60){ output = 'bad'}
if (rating > 60){ output = 'poor'}
if (rating > 70){ output = 'good'}
if (rating > 90){ output = 'excellent'}

3 个答案:

答案 0 :(得分:1)

更好的方法是创造性地使用switch

var output = null;
var rating = parseInt(prompt("Rating?"));
switch (true) {
  case (rating <= 60):
    output = 'bad';
    break;
  case (rating > 90):
    output = 'excellent';
    break;
  case (rating > 70):
    output = 'good';
    break;
  case (rating > 60):
    output = 'poor';
    break;
}
console.log(output);

在这里,线条的正确组织非常重要。

答案 1 :(得分:1)

您可以使用Array#some并迭代一组对象进行评级。优点是良好的可维护对象。

ratings = [
    { value: 60, label: 'bad' },
    { value: 70, label: 'poor' },
    { value: 90, label: 'good' },
    { value: Infinity, label: 'excellent' }
]

function rating(v) {
    var ratings = [{ value: 60, label: 'bad' }, { value: 70, label: 'poor' }, { value: 90, label: 'good' }, { value: Infinity, label: 'excellent' }],
        label;

    ratings.some(function (a) {
        if (v <= a.value) {
            label = a.label;
            return true;
        }
    });
    return label;
}

console.log([12.2, 61, 77.7].map(rating));
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6与Array#find

var ratings = [{ value: 60, label: 'bad' }, { value: 70, label: 'poor' }, { value: 90, label: 'good' }, { value: Infinity, label: 'excellent' }],
    rating = v => ratings.find(a => v <= a.value).label;

console.log([12.2, 61, 77.7].map(rating));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:-1)

如果你的记忆力很好,可以采取一种快速的方式。

&#13;
&#13;
var limits = [60,70,90,100],
     rates = ["bad","poor","good","excellent"],
    grades = limits.reduce((g,c,i,a) => i ? g.concat(Array(c-a[i-1]).fill(rates[i]))
                                          : g.concat(Array(c).fill(rates[0])),[]),
     notes = [12.2, 61, 77.7, 89.5];
notes.forEach(n => console.log(grades[Math.round(n)]));
&#13;
&#13;
&#13;