Javascript程序无法识别if语句

时间:2017-05-18 03:18:25

标签: javascript if-statement

当我期待if语句运行时,程序正在运行else语句。当程序根据gameObject的colorSequence属性检查gameObject的playerSelections属性时,我希望程序记录“你得到它”。要走的路!'如果两个数组是等价的。相反,我不断获得控制台日志声明'下次好运!'。有没有人知道为什么会发生这种情况。 `

const $headerText = $('.fly-in-text');
setTimeout(function() {
    $headerText.removeClass('temp-hide');
}, 500);

let gameObject = {
    colorIds: ['#blue', '#red', '#green', '#yellow'],
    currentLevel: 1,
    colorSequence: [],
    playerSelections: [],
    illuminate:function(color){
        setTimeout(function(){
            $(color).css('opacity', .5);
            setTimeout(function() {
                $(color).css('opacity', 1);
            },500);
        },500);
    },
    levelSequence: function(){
        const iterationCount = this.currentLevel + 2;
        for (let i = 0; i < iterationCount; i++) {
            this.colorSequence.push(this.colorIds[Math.floor(Math.random() * 4)]);
        }
        this.startGame(this.colorSequence);
    },
    startGame: function(sequence) {
        let i = 0;
        const self = this;
        var interval = setInterval(function(){
            self.illuminate(sequence[i]);
            i++;
            if (i >= sequence.length){
                clearInterval(interval);
            }
        }, 1000);
    }
}

$circle.click(function() {
    clearTimeout(interval);
    $(this).toggleClass('rotate');
    gameObject.levelSequence();

    $('.colors').click(function(){
        gameObject.playerSelections.push(`#${this.id}`);
        console.log(gameObject.playerSelections);
        checkForWin();
        // for (let i = 0; i < gameObject.colorSequence.length; i++) {
        //     playerSelections[i] = (`$${this.id}`);
        //     console.log(playerSelections)
        // }
    })
})
function checkForWin(){
    if (gameObject.playerSelections === gameObject.colorSequence){
        console.log('Comparing')
        if (gameObject.playerSelections === gameObject.colorSequence){
            console.log('You got it. Way to go!');
            gameObject.colorSequence = [];
            gameObject.playerSelections = [];
            gameObject.currentLevel += 1;
            $('.colors').off('click');
            return 'You got it. Way to go!';

        } else {
            gameObject.colorSequence = [];
            gameObject.playerSelections = [];
            $('.colors').off('click')
            console.log('Better luck next time!');
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

由于playerSelectionscolorSequence是数组,因此条件gameObject.playerSelections === gameObject.colorSequence测试数组引用是否相等,而不是数组的内容。

您需要检查数组的每个元素是否相等:

How to check identical array in most efficient way?