【发布时间】:2017-05-18 03:18:25
【问题描述】:
当我期望 if 语句运行时,程序正在运行 else 语句。当程序根据游戏对象的 colorSequence 属性检查游戏对象的 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!');
}
}
}
【问题讨论】:
-
gameObject.playerSelections和gameObject.colorSequence都是数组。它们是不同的数组,因此它们永远不会彼此相等。 -
这样比较数组??看到这个:stackoverflow.com/questions/7837456/…
-
您确定您运行的代码与您在上面发布的代码相同吗?您的两个
if语句具有相同的条件表达式。所以如果第一个是true,那么第二个也必须是true。else永远无法运行。但是您的描述说else每次都在运行。这没有意义。