如何根据值计算数组... 我有一个具有此值的数组..
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
我需要根据值
计算数组值为A的数组为2 值B的数组是1
谢谢!
答案 0 :(得分:5)
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);
如果您对内置功能感兴趣......您可以随时添加自己的功能。
Array.prototype.count = function(value) {
var counter = 0;
for(var i=0;i<this.length;i++) {
if (this[i] === value) counter++;
}
return counter;
};
然后你可以像这样使用它。
var result = myArr.count("a");
alert(result);
答案 1 :(得分:4)
哦,好吧,打了一拳,但这是我的版本。
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b"
getCountFromVal( 'a', myArr );
function getCountFromVal( val, arr )
{
var total = arr.length;
var matches = 0;
for( var i = 0; i < total; i++ )
{
if( arr[i] === val )
{
matches++;
}
}
console.log(matches);
return matches;
}
答案 2 :(得分:3)
现场演示: http://jsfiddle.net/CLjyj/1/
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function getNum(aVal)
{
num=0;
for(i=0;i<myArr.length;i++)
{
if(myArr[i]==aVal)
num++;
}
return num;
}
alert(getNum('a')); //here is the use
答案 3 :(得分:1)
我会使用 Array.filter
var arr = ['a', 'b', 'b']
arr.filter(val => val === 'b').length // 2
答案 4 :(得分:0)
每个人都已经给出了明显的功能,所以我将尝试制定另一个解决方案:
var myArr = [];
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function count(arr, value){
var tempArr = arr.join('').split(''), //Creates a copy instead of a reference
matches = 0,
foundIndex = tempArr.indexOf(value); //Find the index of the value's first occurence
while(foundIndex !== -1){
tempArr.splice(foundIndex, 1); //Remove that value so you can find the next
foundIndex = tempArr.indexOf(value);
matches++;
}
return matches;
}
//Call it this way
document.write(count(myArr, 'b'));
答案 5 :(得分:0)
您可以使用Lodash的Published<Value>
函数:
countBy
示例:
_.countBy(myArr);
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
const result = _.countBy(myArr);
// Get the count of `a` value
console.log('a', result.a);
// Get the count of `b` value
console.log('b', result.b);