簡體   English   中英

過濾動態數組值

[英]Filter dynamic Array Values

我需要編碼方面的幫助。

我需要從數組中過濾14個值。 這些值是動態創建的。 我想將值與20.0進行比較,我只需要其中兩個值大於20.0

我把我的希望進入filter的方法開關沒有工作。 先感謝您!

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"
}

為什么不只是映射變量,獲取調整后的值並對其進行過濾。

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內置原型。

我建議使用更好的可迭代數據結構直接使用數組。

函數isBigEnough嘗試檢查是否使用20.0 filtered 由於已filtered undefined這將始終返回false

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

 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) 

更多可重用的方式

在另一個函數中調用isBigEnough

 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) } 

使用咖喱

 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 } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM