3 回答

TA貢獻1786條經(jīng)驗 獲得超11個贊
檢查typeof數(shù)組元素而不是數(shù)組變量。
var arr = [ { move: 10}, {move: function () {}} ];
console.log(typeof arr) // object
console.log(typeof arr[0].move) // number
console.log(typeof arr[1].move) // function
將您的代碼更改為:
while (steps <= 20) {
if (typeof arrayObject[i].move === "function") {
steps += arrayObject[i].move();
turns++;
} else if (typeof arrayObject[i].move === "number")
steps += arrayObject[i].move;
turns++

TA貢獻1799條經(jīng)驗 獲得超8個贊
typeof為您提供一個字符串,因此您需要使用"". 還要比較move屬性而不是對象本身。
您可以根據(jù)自己的目的使用三元運算符,并且可以擁有更優(yōu)雅的代碼。
while (steps <= 20) {
steps += typeof arrayObject[i].move === "function" ? arrayObject[i].move() : arrayObject[i].move;
turns++;
}

TA貢獻1827條經(jīng)驗 獲得超8個贊
1.typeof
返回一個字符串值,需要與 JavaScript 類型的字符串進行比較。
2. 你應(yīng)該測試move
單個項目的屬性arrayObject
是否是一個函數(shù),而不是arrayObject
它本身:
typeof arrayObject[i].move == 'function'
添加回答
舉報