我正在創建pos對象並將它們插入到數組中。在Javascript中插入對象到數組引發未捕獲TypeError
以下是非常好的代碼。
var pos1={lat:25,long:56};
var pos2={lat:100,long:200};
var pos3={lat:-63,long:-29};
var objects=[];
objects.push(pos1);
objects.push(pos2);
objects.push(pos3);
console.log(objects[0].lat+","+objects[0].long);
console.log(objects[1].lat+","+objects[1].long);
console.log(objects[2].lat+","+objects[2].long);
輸出
然後我試圖插入一些對象使用隨機數的loop.It內恰恰是這個論點,這給產生錯誤。
未捕獲的類型錯誤:當名次對象是外循環
var locations=[];
var pos={lat:0,long:0}; //Here post object is outside the loop
size=10;
for(var i=1;i<=size;i++){
var x=Math.floor(1+Math.random()*10);
var y=Math.floor(1+Math.random()*10);
pos.lat=x;
pos.long=y;
locations.push(pos);
}
for(var i=1;i<=size;i++){
console.log(locations[i].lat+","+locations[i].long);
}
輸出
未捕獲的類型錯誤:當名次對象是環路
內部var locations=[];
size=10;
for(var i=1;i<=size;i++){
var pos={lat:0,long:0}; //pos object inside the loop
var x=Math.floor(1+Math.random()*10);
var y=Math.floor(1+Math.random()*10);
pos.lat=x;
pos.long=y;
locations.push(pos);
}
for(var i=1;i<=size;i++){
console.log(locations[i].lat+","+locations[i].long);
}
輸出
我沒有得到爲什麼我收到這些errors.My的理解是,訪問位置陣列,當我需要它種姓到POS對象?
你是不是考慮到數組索引從零開始。 – charlietfl
謝謝@charlietfl我真的很失望,我沒有意識到.........這些都是非常基礎............... –