當我期待if語句運行時,程序正在運行else語句。當程序根據gameObject的colorSequence屬性檢查gameObject的playerSelections屬性時,我希望程序記錄'你明白了。去的路!如果這兩個數組是等價的。相反,我不斷收到控制檯日誌語句「下次更好運氣!」。有沒有人有任何想法,爲什麼這可能會發生。 `Javascript程序不識別if語句
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'是兩個陣列。它們是不同的陣列,所以它們永遠不會彼此相等。 – Xufox
比較這樣的數組? 看到這個:http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript –
也檢查了這一點http://stackoverflow.com/questions/13757109/triple-equal-signs- return-false-for-arrays-in-javascript-why –