2011-12-22 111 views
1

如何取決於值數組我算.. 我有這個值的數組..陣列值計數的JavaScript

var myArr = new Array(3); 
myArr[0] = "a"; 
myArr[1] = "a"; 
myArr[2] = "b"; 

我需要根據值的陣列來算

值爲A的數組爲2 數組B的值爲1

謝謝!

回答

4
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); 
+0

好吧,謝謝,我只是想有一個內置功能它:D – user1033600 2011-12-22 17:20:25

+0

@ user1033600添加了函數的原型版本。 – jessegavin 2011-12-22 17:31:45

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 
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; 
} 
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')); 

Demo