js 二维数组比较大小问题。

报错:Uncaught TypeError: Cannot read property '1' of undefined

console.log()能访问到数字,为什么比较时就会出错?

<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>


达令说
浏览 434回答 1
1回答

陪伴而非守候

这个报错是溢出数组,现在data.length=6,当i=5是,i+1=6就溢出了。<p id="abc">aaaaaa</p><script>var data = [&nbsp; ["北京", 10],&nbsp; ["上海", 20],&nbsp; ["福州", 30],&nbsp; ["广州", 40],&nbsp; ["成都", 40],&nbsp; ["西安", 100]];var abc = document.getElementById('abc');j = 0;for (var i = 0; i < data.length; i++) {&nbsp; &nbsp; console.log(data[i][1]);&nbsp; &nbsp; if(i<data.length-1){&nbsp; &nbsp; &nbsp; &nbsp; if (data[i][1] > data[i+1][1]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j++;&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }}abc.innerHTML = j;</script>这样就不会报错了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript