简体   繁体   中英

JS 2D array cannot read property of undefined

So I have an array items, that always has 7 columns. Using the code provided, I can display each element of the array with out error. However when I try to access the array at the end like this:

<button onclick="delete_item(items[i][6])">Delete</button>

I get:

Uncaught TypeError: Cannot read property '6' of undefined
    at HTMLButtonElement.onclick (account.php:64)
onclick @ account.php:64

Rest of my code is:

for(i=0;i<items.length;i++){
                document.write('<div style="border-style:solid;padding:15px;background-color:whitesmoke;"><img src="'+items[i][5]+'" style="width:8%"><br><b style="font-size:20px;">'+items[i][0]+'</b><br>$'+items[i][1]+'<div style="float:right"><a href="item.php?itemid='+items[i][6]+'&itemname='+items[i][0]+'" style="font-size:20px">Click Here for the Item Information</a></div><br>Seller: '+items[i][2]+'<br>Description: '+items[i][3]+'<br> <button onclick="delete_item(items[i][6])">Delete</button></div>');
document.write('<br>');
                }

Also, by using <button onclick="delete_item(items[1][6])">Delete</button> instead of using 'i', everything works fine. What would cause this, because shouldn't using i

Use this below one because in your code snapshot, I not referring index. Its trey to read I kay from your array and that not available, try below code:

<button onclick="delete_item(items["+i+"][6])">Delete</button>

You have to add some quotes around your variable:

'<button onclick="delete_item(\\''+items[i][6]+ '\\')">Delete</button>'

 let a = ["a","b","c","d","e","f","g"]; let b = ["x","b","c","d","e","f","y"]; let items = [a,b]; var delete_item = function(item){ console.log("delete: " + item) } for (i = 0; i < items.length; i++) { document.write('<div style="border-style:solid;padding:15px;background-color:whitesmoke;"><img style="width:8%"><br><b style="font-size:20px;">' + items[i][0] + '</b><br>$' + items[i][1] + '<div style="float:right"></div><br>Seller: ' + items[i][2] + '<br>Description: ' + items[i][3] + '<br> <button onclick="delete_item(\\''+items[i][6]+ '\\')">Delete</button></div>'); document.write('<br>'); } 

Also, you could consider using document.createElement and addEventListener .

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