Reputation: 69
var nodesXY = ['15% 15%','30% 16%','19% 42%','39% 80%',];
var number = ["0","1","2","3","4","0","0","0"];
//some loop
AccesNodes(number[1]);
function AccesNodes(number){
console.log(number);
//number = number;
var firstNode = nodesXY[number];
console.log(nodesXY[number]);
console.log(firstNode);
number++;
var secondNode = nodesXY[number];
console.log(nodesXY[number]);
console.log(secondNode);
number = number + 4;
var secondNode = nodesXY[number];
console.log(nodesXY[number]);
console.log(secondNode);
}
I don't get an undefined
when I log the firstNode
however when I calculate the number into "the next node" and try to get var secondNode = nodesXY[number+1];
I get an undefined. Why won't this work?
Is there any other way to get this? I've searched all over.
Upvotes: 1
Views: 58
Reputation: 106
Your array number
contains elements of type string
. Even though JavaScript is not type-strong, variables and elements still contain data of some specific type.
When you access number[X]
, it will therefore return a string. In order to make it work, you'll have to create an array of numbers: var number = [1,2,3,...]
or parse the string returned from the array into a number using parseInt(number[X])
.
For a list of the different types a JavaScript var
can hold, see this page in the MDN JavaScript documentation.
Upvotes: 1
Reputation: 395
Your numbers array contains strings not actual numbers "1" + 1
will yield "11"
instead of 2
which isn't a key in your array. Either use number = [0,1,...]
or use parseInt(number) + 1
.
Upvotes: 1
Reputation: 756
Use numbers in your number array, not strings
var number = [0,1,2,3,4,0,0,0];
Upvotes: 1