var model =
{
numShips:3,
boardSize:7,
shipLength:3,
shipSunk:0,
ships:[
{
locations: ["10","20","30"],
hits : ["hit","","hit"]
},
{
locations:["20","21","22"],
hits:["hit","",""]
},
{
locations:["33","34","35"],
hits:["hit","hit","hit"]
}
],
fire:function(guess)
{
for(var i=0;i<model.ships.length;i++)
{
for(var j=0;j<model.ships.locations.length;j++)
{
if(guess==(model.ships[i].locations[j]))
{
model.ships[i].hits[j]="hit";
console.log(model.ships[i].hits[j]);
}
}
}
}
};
model.fire(21);
我只是想检查一下,如果我通过guess的值等于locations数组的任何值,然后如果它有,那么我只是更新其相应的命中数组并将该位置标记为命中。但是这给了我像.length属性没有定义的错误。你可以帮帮我吗?
答案 0 :(得分:4)
在第二个for循环中,您希望从第一个for循环遍历ship的位置。您需要通过索引访问它:
for(var j=0;j<model.ships[i].locations.length;j++) ...
// -----------------------^
答案 1 :(得分:0)
正如我已经评论过的那样,ships
是一个数组,你必须循环它并检查currentIteration.location.length
您无需在locations
上使用循环进行匹配。您可以使用array.indexOf()
获取索引并使用item.hits[index]
您可以尝试这样的事情:
var model = {
numShips: 3,
boardSize: 7,
shipLength: 3,
shipSunk: 0,
ships: [{
locations: ["10", "20", "30"],
hits: ["hit", "", "hit"]
}, {
locations: ["20", "21", "22"],
hits: ["hit", "test", ""]
}, {
locations: ["33", "34", "35"],
hits: ["hit", "hit", "hit"]
}],
fire: function(guess) {
model.ships.forEach(function(item) {
var _index = item.locations.indexOf(guess.toString());
if(_index>=0){
console.log(item.hits[_index])
}
})
}
};
model.fire(21);
&#13;