1

This is my code: I want to get the first value of the arrays in every property, but it doesnt work. Thanks for help.

var arena = {
 o1: ['gate',1,1],
 o2: ['block',1,1]
};
$(document).ready(function(){
 var canvas = document.getElementById('canvas.arena');
 var xpercent = canvas.width/100;
 var ypercent = canvas.height/100;
 for (var key in arena) {
 if (arena.hasOwnProperty(key)) {
 console.log(key + " -> " + arena[key[0]]);
 }
 }
});
asked Feb 5, 2018 at 15:19
1
  • 1
    Try arena[key][0]... Commented Feb 5, 2018 at 15:20

2 Answers 2

2

Almost:

for (var key in arena) {
 console.log(key + " -> " + arena[key][0]);
}

key will always be a property, no need to check.

answered Feb 5, 2018 at 15:20

6 Comments

sure you need to check, some framework may extend the Object's prototype and it will be also included as key
any example of that?
Object.prototype.sth = null. Now execute your code and you will get Uncaught TypeError: Cannot read property '0' of null
@adassko then one should not use such a crappy lib at all. Thats what the enumerable flag is for.
@JonasW. sure but why not just make this code bulletproof by adding this simple flag check. the prototype might be even extended later in some random place by some evil, vindictive developer and it will be hard to debug at first. something like "#define true ((__LINE__&15)!=15)" ;)
|
0

you are very close:

var arena = {
 o1: ['gate',1,1],
 o2: ['block',1,1]
};
$(document).ready(function(){
 for (var key in arena) {
 console.log(key + " -> " + arena[key][0]);
 }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

prepared this fiddle:

https://jsfiddle.net/njvf58ow/1/

answered Feb 5, 2018 at 15:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.