I am attempting to split a string of integers into an array in JavaScript.
Originally I had:
m.rows[7] = new Array (8,11);
And I am changing it to:
var nearby = nearby.split(",");
m.rows[7] = new Array (nearby);
(And setting a variable with the appropriate integers separated by a comma in my level editor. When I print “nearby[0]” to the console I get ‘8’. When I print “nearby[1]” to the console I get 11)
However, I then have this code in which I attempt to match one of the elements in the array with an element in another array:
for (var i = m.rows[id].length-1; i >= 0; i--) {
// If the loop finds an element ID that matches the ID of the last element in the path array, do this:
console.log('test nearby 2: ' + m.rows[id][i]);
if (m.rows[id][i] == this.path_array[this.path_array.length-1].id) {
// Loop through the one array
for (var j = all_nodes.length-1; j >= 0; j--){
// If the ID of one of one of these entities matches the id of the instance that was just clicked
if (all_nodes[j].id == id) {
// Activate that node:
all_nodes[j].active = true;
}
}
break;
}
When I actually put “8,11” into the array above manually the above works perfectly. However when I attempt to use “nearby” which I split into the array, it does not. And printing it to the console in “test nearby 2” above, when I use “nearby” “8,11” gets printed. When I manually enter “8,11” into that array I get “11”.
I’m fairly new to JavaScript so I’m probably missing something extremely obvious here – can anyone shed some light?
Thanks!
That’s not how arrays work. In
new Array(8, 11),8and11are parameters. Innew Array(nearby),nearbyis one parameter. To achieve the functionality you need, however, it’s quite simple;nearbyis already an array, so just assign it:Or, if the type bothers you:
Note that here I used the array literal syntax,
[].[a, b]is basically equivalent tonew Array(a, b), and you should use the literal syntax when possible for various reasons.