簡體   English   中英

Javascript檢查數組的元素

[英]Javascript check on array's elements

我如何檢查一個數組,如果它的元素全為0,而1為1?

樣品:

array = [0, 0, 0, 1, 0];
check(array); //returns the index where it is 1 which is 3

array = [0, 3, 0, 2, 0];
check(array); //returns -1

array = [0, 3, 1, 2, 0];
check(array); //returns -1 again if there are non zero aside from 1, it should be one 1 and others are all 0.

array = [0, 0, 1, 0, 1];
check(array); //returns -1 again, there should just be one element of 1
function check(a) {
    var index = -1;
    for (var i = 0; i < a.length; i++) {
        if (a[i] == 1) {
            if (index < 0) {
                index = i;
            } else {
                return -1;
            }
        } else if (a[i] != 0) {
            return -1;
        }
    }
    return index;
}

array1 = [0, 0, 0, 1, 0];
check(array1); //returns 3

array2 = [0, 3, 0, 2, 0];
check(array2); //returns -1

您可以使用幾個過濾器,從原始數組中生成一個無效數字數組(即非0或1),然后生成一個數字數組。 最后,您可以檢查這些結果數組的長度,以查看是否滿足您的條件。

var others = a.filter(function(_item) { return (_item !== 1 && _item !== 0); }),
    ones = a.filter(function(_item) { return (_item === 1); });

if(others.length === 0 && ones.length === 1) {
    // valid
}

如果保證數組元素為非負數,則可以對數組的所有元素求和。 如果sum不為1,則不是您想要的數組。 您不必循環數組元素即可計算元素總和。 使用新的JavaScript Array的reduce函數。 在網絡上查找。

如果數組元素也可以是負數,則事情可能變得復雜。

暫無
暫無

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

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