繁体   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