找出数组元素出现的次数

时间:2012-11-14 23:49:02

标签: javascript arrays

我是JavaScript新手,我已经学习和练习了大约3个月,希望我能在这个主题上得到一些帮助。我正在制作扑克游戏,而我正在尝试做的是确定我是否有一对,两对,三种,四种或满屋。

例如,在[1, 2, 3, 4, 4, 4, 3]中,1出现一次,4出现三次,依此类推。

我怎么可能要求我的电脑告诉我一个数组元素出现多少次?

解决了,这是最终产品。

    <script type="text/javascript">
    var deck = [];
    var cards = [];
    var convertedcards = [];
    var kinds = [];
    var phase = 1;
    var displaycard = [];
    var options = 0;
    var endgame = false;

    // Fill Deck //
    for(i = 0; i < 52; i++){
        deck[deck.length] = i;          
    }

    // Distribute Cards //
    for(i = 0; i < 7; i++){
        cards[cards.length] = Number(Math.floor(Math.random() * 52));
        if(deck.indexOf(cards[cards.length - 1]) === -1){
            cards.splice(cards.length - 1, cards.length);
            i = i - 1;
        }else{
            deck[cards[cards.length - 1]] = "|";
        }
    }

    // Convert Cards //
    for(i = 0; i < 7; i++){
        convertedcards[i] = (cards[i] % 13) + 1;
    }


    // Cards Kind //
    for(i = 0; i < 7; i++){
        if(cards[i] < 13){
            kinds[kinds.length] = "H";
        }else if(cards[i] < 27 && cards[i] > 12){
            kinds[kinds.length] = "C";
        }else if(cards[i] < 40 && cards[i] > 26){
            kinds[kinds.length] = "D";
        }else{
            kinds[kinds.length] = "S";
        }
    }

    // Card Display //
    for(i = 0; i < 7; i++){
        displaycard[i] = convertedcards[i] + kinds[i];
    }

    // Hand Strenght //
    var handstrenght = function(){
        var usedcards = [];
        var count = 0;
        var pairs = [];
        for(i = 0, a = 1; i < 7; a++){
            if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
                pairs[pairs.length] = convertedcards[i];
                usedcards[a] = "|";
            }else if(a > 6){
                i = i + 1;
                a = i;
            }
        }

        // Flush >.< //
        var flush = false;
        for(i = 0, a = 1; i < 7; i++, a++){
            if(kinds[i] === kinds[a] && kinds[i] != undefined){
                count++;
                if(a >= 6 && count >= 5){
                    flush = true;
                    count = 0;
                }else if(a >= 6 && count < 5){
                    count = 0;
                }
            }
        }
        // Straight >.< //
        var straight = false;
        convertedcards = convertedcards.sort(function(a,b){return a-b});
        if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
            convertedcards[0] = 14;
            convertedcards = convertedcards.sort(function(a,b){return a-b});
        }
        alert(convertedcards);
        if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
            straight = true;
        }else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
            straight = true;
        }else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
            straight = true;
        }
        // Royal Flush, Straight Flush, Flush, Straight >.< //
        var royalflush = false;
        if(straight === true && flush === true && convertedcards[6] === 14){
            royalflush = true;
            alert("You have a Royal Flush");
        }
        else if(straight === true && flush === true && royalflush === false){
            alert("You have a straight flush");
        }else if(straight === true && flush === false){
            alert("You have a straight");
        }else if(straight === false && flush === true){
            alert("You have a flush");
        }
        // Full House >.< //
        if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
            fullhouse = true;
            alert("You have a fullhouse");
        }else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
            fullhouse = true;
            alert("You have a fullhouse");
        }else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
            fullhouse = true;
            alert("You have a fullhouse");
        }
        // Four of a kind >.< //
        else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
            alert("You have four of a kind");
        }
        // Three of a kind >.< //
        else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
            alert("You have three of a kind");
        }
        // Double Pair >.< //
        else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
            alert("You have a double pair");
        }
        // Pair >.< //
        else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
            alert("You have a pair");
        }
        alert(pairs);
    };
    while(endgame === false){
        if(phase === 1){
            options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
        }else if(phase === 2){
            options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
        }else if(phase === 3){
            options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
        }else if(phase === 4){
            options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
        }
        switch(options){
            case 1:
                    if(phase === 5){
                        handstrenght();
                        endgame = true;
                    }else{
                        phase++;
                    }
                    break;
            case 2:
                    endgame = true;
                    break;
            default:
                    endgame = true;
                    break;
        }
    }


</script>

6 个答案:

答案 0 :(得分:28)

  • 保留总计数的变量
  • 遍历数组并检查当前值是否与您要查找的值相同,如果是,则将总计数增加一个
  • 循环后,总计数包含您要查找的数字在数组
  • 中的次数

显示您的代码,我们可以帮助您找出出错的地方

这是一个简单的实现(因为你没有不起作用的代码)

var list = [2, 1, 4, 2, 1, 1, 4, 5];  

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3

countInArray也可以实现为

function countInArray(array, what) {
    return array.filter(item => item == what).length;
}

更优雅,但可能不那么高效,因为它必须创建一个新数组。

答案 1 :(得分:7)

使用filterlength看起来很简单,但会浪费大量内存。

如果你想使用漂亮的数组方法,那么合适的方法是reduce

function countInArray(array, value) {
  return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3

答案 2 :(得分:4)

嗯..

var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
  if (typeof acc[curr] == 'undefined') {
    acc[curr] = 1;
  } else {
    acc[curr] += 1;
  }

  return acc;
}, {});

// a == {2: 5, 4: 1, 5: 3, 9: 1}

从这里: Counting the occurrences of JavaScript array elements

或者您也可以在那里找到其他解决方案..

答案 3 :(得分:3)

定位最近的浏览器时,您可以使用filter()。 (MDN页面还为该功能提供了polyfill。)

var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;

您甚至可以将过滤功能抽象为:

// Creates a new function that returns true if the parameter passed to it is 
// equal to `x`
function equal_func(x) {
    return function(it) {
        return it === x;
    }
}
//...
var result = items.filter(equal_func(4)).length;

答案 4 :(得分:1)

这是Juan的答案的实现:

function count( list, x ) {

    for ( var l = list.length, c = 0; l--; ) {

        if ( list[ l ] === x ) {

            c++;
        }
    }

    return c;

}

更短:

function count( list, x ) {

    for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );

    return c;

}

答案 5 :(得分:1)

这是一个使用Array Object Prototype的实现,并且具有额外的功能级别,如果没有提供搜索项,则返回长度:

Array.prototype.count = function(lit = false) {
    if ( !lit ) { return this.length}
    else {
        var count = 0;
        for ( var i=0; i < this.length; i++ ) {
            if ( lit == this[i] ){
                count++
            }
        }
        return count;
    }
}

这个用法非常简单,如下:

var count = [1,2,3,4,4].count(4);  // Returns 2
var count = [1,2,3,4,4].count();   // Without first parameter returns 5