Error: Uncaught TypeError: Cannot read property '1' of undefined
console.log() can access numbers, why does an error occur during comparison?
<p id="abc">aaaaaa</p>
<script>
var data = [
["北京", 10],
["上海", 20],
["福州", 30],
["广州", 40],
["成都", 40],
["西安", 100]
];
var abc = document.getElementById('abc');
j = 0;
for (var i = 0; i < data.length; i++) {
console.log(data[i][1]);
if (data[i][1] > data[i+1][1]) {
j++;
};
}
abc.innerHTML = j;
</script>
高洛峰2017-06-26 10:57:26
This error is an overflow array. Now data.length=6. When i=5, i+1=6 overflows.
<p id="abc">aaaaaa</p>
<script>
var data = [
["北京", 10],
["上海", 20],
["福州", 30],
["广州", 40],
["成都", 40],
["西安", 100]
];
var abc = document.getElementById('abc');
j = 0;
for (var i = 0; i < data.length; i++) {
console.log(data[i][1]);
if(i<data.length-1){
if (data[i][1] > data[i+1][1]) {
j++;
};
}
}
abc.innerHTML = j;
</script>
This way there will be no errors.
淡淡烟草味2017-06-26 10:57:26
You can write like this:
var data = [
["北京", 10],
["上海", 20],
["福州", 30],
["广州", 40],
["成都", 40],
["西安", 100]
];
var abc = document.getElementById('abc');
var j = 0;
var max = data[0][1];
for (let i = 1; i < data.length; i++) {
let temp = data[i][1];
if (temp > max) {
j = i;
max = temp;
}
}
abc.innerHTML = data[j][0];
淡淡烟草味2017-06-26 10:57:26
因为数组越界了,当i = data.length - 1的时候, data[i+1][1]访问的就是 data[6][1],data[6]其实是没有的,因为他最大的才是data[5], 说的有点乱,不知道能看懂不