过滤动态数组值

时间:2017-10-24 13:02:48

标签: javascript arrays

我需要编码方面的帮助。

我需要从数组中过滤掉14个值。 值是动态创建的。 我想将值与20.0进行比较 我只需要两个值高于20.0

我把我的希望寄托在filter方法中,因为Switch不起作用。 提前谢谢!

if (!Array.prototype.filter) {
    Array.prototype.filter = function (fun /*, thisp*/) {
        var len = this.length;

        if (typeof fun != "function")
            throw new TypeError();

        var res = new Array();
        var thisp = arguments[1];

        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, this))
                    res.push(val);
            }
        }
        return res;
    };
}

function isBigEnough(element, index, array) {
    return (filtered >= 20.0);
}

var filtered = [
    (vol1l * 100).toFixed(1),
    (vol2l * 100).toFixed(1),
    (vol3l * 100).toFixed(1),
    (vol4l * 100).toFixed(1),
    (vol5l * 100).toFixed(1),
    (vol6l * 100).toFixed(1),
    (vol7l * 100).toFixed(1),
    (vol1r * 100).toFixed(1),
    (vol2r * 100).toFixed(1),
    (vol3r * 100).toFixed(1),
    (vol4r * 100).toFixed(1),
    (vol5r * 100).toFixed(1),
    (vol6r * 100).toFixed(1),
    (vol7r * 100).toFixed(1)
].filter(isBigEnough);

if (filtered) {
    testText.textContent = "JA! Gerät"
} else {
    testText.textContent = "NO! Nein"
}

2 个答案:

答案 0 :(得分:2)

为什么不只是映射变量,获取调整后的值并过滤它。

const
    factor100 = v => 100 * v,
    isBigEnough = v => v >= 20;

var filtered = [vol1l, vol2l, vol3l, vol4l, vol5l, vol6l, vol7l, vol1r, vol2r, vol3r, vol4r, vol5r, vol6r, vol7r]
        .map(factor100)
        .filter(isBigEnough);

此提案适用于Array的内置原型。

我建议使用更好的可迭代数据结构直接使用数组。

答案 1 :(得分:1)

该功能很大,试着用filtered检查20.0。这将始终返回false,因为filteredundefined

代码

function isBigEnough(element, index, array) {
    return (element >= 20.0);
}

实施例

&#13;
&#13;
function isBigEnough(element, index, array) {
    return (element >= 20.0);
}

var filtered = [1.0.toFixed(1), 2.0.toFixed(1), 20.0.toFixed(1), 21.0.toFixed(1)].filter(isBigEnough)

console.log(filtered)
&#13;
&#13;
&#13;

更多可重用方式

在其他功能中调用isBigEnough

&#13;
&#13;
var values = [1, 2, 10, 11, 20, 22].filter(biggerThan10)
var moreValues = values.filter(biggerThan20)

console.log(values, moreValues)

function isBigEnough(value, compareValue) {
    return (value >= compareValue);
}

function biggerThan10(value) {
    return isBigEnough(value, 10)
}

function biggerThan20(value) {
    return isBigEnough(value, 20)
}
&#13;
&#13;
&#13;

使用Currying

&#13;
&#13;
var biggerThan10 = isBigEnough(10)
var biggerThan20 = isBigEnough(20)
var values = [1, 2, 10, 11, 20, 22].filter(biggerThan10)
var moreValues = values.filter(biggerThan20)

console.log(values, moreValues)

function isBigEnough(value, compareValue) {
    return (value >= compareValue);
}

function isBigEnough(compareValue) {
    return function(value) {
        return compareValue <= value
    }
}
&#13;
&#13;
&#13;