Reputation: 7018
How do I get values of array into global variable?
var p = new Array();
var all_Y_values = 0;
for (var r = 0; r < embeddedCells.length; r++)
{
p[r] = embeddedCells[r].attributes.position.y;
all_Y_values = p[r], all_Y_values;
console.log("all y values: " + all_Y_values); //prints all values
}
console.log("all y values: " + all_Y_values); //prints only last value
Right now inside the loop I am able to print all values inside loop but when I print the same outside loop its printing only last value.
Upvotes: 1
Views: 222
Reputation: 695
This should print all y values at the end (ps : new version using forEach)
var p = new Array();
embeddedCells.forEach (function (e, i) {
p[i] = e.attributes.position.y;
console.log("current y value: " + p[i]); //prints current value
});
console.log("all y values: " + p.join(", "));
Hope it works
Upvotes: 2
Reputation: 172
Your collection of values is already inside "p":
var p = new Array();
var all_Y_values = 0;
for (var r = 0; r < embeddedCells.length; r++) {
p[r] = embeddedCells[r].attributes.position.y;
console.log("current y value: " + p[r]); //prints current value
}
console.log("all y values: " + p.join(','));
p.s. : p and all_Y_values are not global, but local variables. In javascript only, function create a new context. Loops are not.
Upvotes: 3