错误:未定义 .lenth 属性

ERROR : .lenth property is not defined?

本文关键字:属性 lenth 未定义 错误      更新时间:2023-09-26
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);

只想检查我通过猜测传递的值是否等于位置数组的任何值,然后如果有,那么我只会更新其相应的命中数组并将该位置标记为命中。但这给了我错误,例如未定义 .length 属性。你能帮我吗?

在第二个 for 循环中,您希望从第一个 for 循环迭代船舶的位置。您需要按索引访问它:

for(var j=0;j<model.ships[i].locations.length;j++) ...
// -----------------------^

正如我已经评论过的,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);