簡體   English   中英

計算Javascript數組索引的出現次數

[英]Counting occurrences of Javascript array indexes

我有以下數組。

       "APP-A": {
            "active": true
        },
        "APP-B": {
            "active": true
        },
        "APP-C": {
            "active": true
        },
        "BOOL-A": {
            "active": true
        },
        "BOOL-B": {
            "active": true
        },
        "BOOL-C": {
            "active": true
        },

我需要獲取數組中APP- *的總數。 我正在嘗試在有角JS中實現。 普通JS中的解決方案也將有所幫助。

TIA

一種方法是在對象的鍵上使用.filter()

var count = Object.keys(obj).filter(function (key) {
    return key.indexOf(prefix) === 0;
}).length;

http://jsfiddle.net/4m692usx/1/

可以這樣嘗試:

var items = { "APP-A": {
        "active": true
    },
    "APP-B": {
        "active": true
    },
    "APP-C": {
        "active": true
    },
    "BOOL-A": {
        "active": true
    },
    "BOOL-B": {
        "active": true
    },
    "BOOL-C": {
        "active": true
    }
};
var c=0;
for(var item in items)
{
if(item.indexOf("APP-") >= 0)      
c++;
}
console.log(c);// your count here.

檢查此JSFiddle Link

但實際上它不是數組,而是JSON對象 我們正在計算的是JSON鍵。

JS部分:

var items = { "APP-A": {
            "active": true
        },
        "APP-B": {
            "active": true
        },
        "APP-C": {
            "active": true
        },
        "BOOL-A": {
            "active": true
        },
        "BOOL-B": {
            "active": true
        },
        "BOOL-C": {
            "active": true
        }
};

var app_count = 0;
for(var ik in items) {
    if(ik.indexOf("APP-") >= 0) {
        app_count++;
    }
}
alert(app_count);
console.log(app_count);

 var myArray = { "APP-A": { "active": true }, "APP-B": { "active": true }, "APP-C": { "active": true }, "BOOL-A": { "active": true }, "BOOL-B": { "active": true }, "BOOL-C": { "active": true } }; var reg = /^APP-/, count = 0, name; for (name in myArray) { count += reg.test(name); } document.getElementById('output').innerHTML = count; 
 <div id="output"></div> 

看起來像json,而不是數組。

var count = 0;
for (var key in json) {
    key.indexOf('APP-')!==-1?count++,count;
}

你可以做這樣的事情。

http://jsfiddle.net/098o3kch/1/

var items = { "APP-A": {
            "active": true
        },
        "APP-B": {
            "active": true
        },
        "APP-C": {
            "active": true
        },
        "BOOL-A": {
            "active": true
        },
        "BOOL-B": {
            "active": true
        },
        "BOOL-C": {
            "active": true
        }
};

function getCount(obj,pattern){
var cnt = 0;
 for(var item in obj)
{
if(item.indexOf(pattern) >= 0)  
cnt++;
}
return cnt;
 }

alert(getCount(items, "APP-"));

暫無
暫無

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

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