通过数组检查多个值,应返回一个值

时间:2018-08-12 19:06:57

标签: javascript arrays

所有检查后如何返回一个值? 在此示例中,方法checkInterval()被调用四次并覆盖结果。 如果const VALUES中的至少一个值超出范围(PRESCRIPTION_RULES),我需要返回false。

const PRESCRIPTION_RULES = {
    interval: {
        SPH: [{min: -2, max: 2}],
        CYL: [{min: -2, max: 2}],
    },
};

class CheckRules {

    check() {

        const values = [
            {name: 'sph_od', value: -2},
            {name: 'sph_os', value: -2},
            {name: 'cyl_os', value: -5},
            {name: 'cyl_od', value: -1},
        ];

        values.map(obj => {
            if (obj.name === 'sph_od' || obj.name === 'sph_os') {
               this.checkInterval(obj.value, PRESCRIPTION_RULES.interval.SPH);
            } else if (obj.name === 'cyl_od' || obj.name === 'cyl_os') {
              this.checkInterval(obj.value, PRESCRIPTION_RULES.interval.CYL);
            }
        });

    }

    checkInterval(current, packages) {
        let result = [];

        packages.map(obj => {
            if (obj.min <= current && obj.max >= current) {
               result.push(true);
            }
            else {
                result.push(false);
            }
        });
        
        const shouldReturnOneValue = result.every(elem => elem === true);
        console.log(shouldReturnOneValue);
    }

}

const rules = new CheckRules();
rules.check();

这是我的课堂的简化版本,我删除了所有不相关的内容。我有很多PRESCRIPTION_RULES和VALUES

链接到沙盒https://jsbin.com/qoweyow/edit?js,console

1 个答案:

答案 0 :(得分:1)

假设您遵守所有规则,则希望check()返回一个布尔值:

使checkInterval返回result.every()的值:

checkInterval(current, packages) {
        // you can use filter here instead of map to filter eleements, then every
        return packages.filter(obj => {
           return obj.min <= current && obj.max >= current 
        }).every(elem => elem === true);
    }

在check()中,将地图更改为每个地图并返回结果

return values.every(obj => {
            if (obj.name === 'sph_od' || obj.name === 'sph_os') {
               return this.checkInterval(obj.value, PRESCRIPTION_RULES.interval.SPH);
            } else if (obj.name === 'cyl_od' || obj.name === 'cyl_os') {
              return this.checkInterval(obj.value, PRESCRIPTION_RULES.interval.CYL);
            }
        });