数组值计数javascript [英] Array value count javascript
本文介绍了数组值计数javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据值计算数组..
我有一个具有此值的数组..
How can I count the array depending on the value.. I have an array with this value..
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
我需要根据值计算数组
数值A的数组是2
数值B的数组是1
Array with Value A is 2 Array with value B is 1
谢谢!
推荐答案
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function count(array, value) {
var counter = 0;
for(var i=0;i<array.length;i++) {
if (array[i] === value) counter++;
}
return counter;
}
var result = count(myArr, "a");
alert(result);
如果您对内置功能感兴趣...您可以随时添加自己的功能。
If you're interested in a built-in function... you could always add your own.
Array.prototype.count = function(value) {
var counter = 0;
for(var i=0;i<this.length;i++) {
if (this[i] === value) counter++;
}
return counter;
};
然后你可以像这样使用它。
Then you could use it like this.
var result = myArr.count("a");
alert(result);
这篇关于数组值计数javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文