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]]);
}
}
});
2 Answers 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
Adassko
sure you need to check, some framework may extend the Object's prototype and it will be also included as key
yBrodsky
any example of that?
Adassko
Object.prototype.sth = null
. Now execute your code and you will get Uncaught TypeError: Cannot read property '0' of null
Jonas Wilms
@adassko then one should not use such a crappy lib at all. Thats what the
enumerable
flag is for.Adassko
@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)"
;) |
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:
answered Feb 5, 2018 at 15:23
Comments
lang-js
arena[key][0]
...