计算 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中的解决方案也将有所帮助。
蒂亚
一种方法是在对象的键上使用.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.
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;
}
检查此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);
你可以做这样的事情。
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-"));
相关文章:
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 将Javascript数组发送到控制器ASP.NET MVC
- JavaScript数组包含一个值
- 将JavaScript数组传递给函数
- javascript:数组循环
- 将数据存储在javascript数组中以供进一步使用
- 在Javascript数组中查找绝对最大值
- JavaScript数组优化以提高性能
- 在javascript数组中分散数字
- 如何发送分配列表<字符串>到JavaScript数组或可枚举对象
- Javascript数组动态
- javascript数组元素是否知道其封闭数组
- 将 JSON 数组解析为 JavaScript 数组
- 将Transform和Instance Variable转换为对象的JavaScript数组
- 使用Web Html表单创建Javascript数组
- 从重复的javascript数组结果集中只获取一行
- 如何为Javascript数组()的使用准备PHP变量
- Javascript数组和函数
- 为DataTables aoColumnDefs创建JavaScript数组(JSON格式)