简体   繁体   中英

Uncaught TypeError: Cannot read property '0' of undefined on array 2d

 var input = [
            ["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"],
            ["0002", "Dika Sembiring", "Medan", "10/10/1992", "Bermain Gitar"],
            ["0003", "Winona", "Ambon", "25/12/1965", "Memasak"],
            ["0004", "Bintang Senjaya", "Martapura", "6/4/1970", "Berkebun"]
        ]

        function dataHandling(input){
            for (var i =0; i <= input.length; i++){

                var id = "Nomor ID: " + input [i][0];
                var nama = "<br>Nama Lengkap: " + input [i][1] ;
                var ttl = "<br>TTL: " + input[i][2] +" "+ input [i][3];
                var hobi = "<br>Hobi: " + input[i][4];
                jawaban2 += id + nama + ttl + hobi;
                // Isikan outputnya di sini
            }
            document.getElementById("jawaban2").innerHTML = jawaban2;
        }


        dataHandling(input); 

can someone explain the error, how 0 be defined? bcause this is thr number of data in my array 2d. i've no idea

The cause for your error is this:

for (var i =0; i <= input.length; i++)

If you put as loop ending condition i <= array.length you are searching for a position that doesn't exist on the last loop. Your array has 4 elements, so the positions you are looking for are 0, 1, 2 and 3. Position 4 doesn't exist, and yet you are trying to access it when i equals input.length .

A for loop should always be either:

for (var i = 0; i < array.length; i++)

or

for (var i = 0; i <= array.length -1; i++)

This way you make sure you stay inside your array.

var input = [
            ["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"],
            ["0002", "Dika Sembiring", "Medan", "10/10/1992", "Bermain Gitar"],
            ["0003", "Winona", "Ambon", "25/12/1965", "Memasak"],
            ["0004", "Bintang Senjaya", "Martapura", "6/4/1970", "Berkebun"]
        ]

        function dataHandling(input){
            for (var i =0; i <= input.length-1; i++){

                var id = "Nomor ID: " + input [i][0];
                var nama = "<br>Nama Lengkap: " + input [i][1] ;
                var ttl = "<br>TTL: " + input[i][2] +" "+ input [i][3];
                var hobi = "<br>Hobi: " + input[i][4];
                 jawaban2 += id + nama + ttl + hobi;
                // Isikan outputnya di sini
            }
           document.getElementById("jawaban2").innerHTML = jawaban2;
        }


        dataHandling(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM