I have an object and an array:
m = { "1": ["2", "3"], "6": ["4", "5"] };
var p = ["1", "6"];
I have a for loop:
for (var i = 0; i < p.length; i++) {
// Return an array that is the value of a key in m, for each key specified in p
var array = m[p[i]];
// do stuff with array
}
Any reason why the above does not work? array is still undefined after the for loop runs.
Your declaration of
m = { "1": ["2", "3"], "6", ["4", "5"] };gives syntax error for me. I assume you meanm = { "1": ["2", "3"], "6": ["4", "5"] };.p.lengthis 2, so you have 2 iterations of the loop. In first iteration values of your expressions are:In second loop:
You have only
m["1"]andm["6"], nom["2"]. That’s whyarrayis undefined in the last iteration. So it remains undefined after the loop.You may correct
mdeclaration as following:Now you will get
array = ["4", "5"]after the loop.I can advise you not to store integers in strings. Use
2instead of"2". Otherwise it can cause errors in the future. For example,2 + 2 = 4and"2" + "2" = "22". If you have"2"from some other code, useparseIntto convert it to a normal number.Also, you don’t have to create
pvariable with list of keys. You can simply usefor..inloop to iterate through keys of your object:Keep in mind that
for..indoesn’t guarantee to preserve the order of keys. However, all existing implementations offor..indo preserve the order.