1

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.

4
  • all_Y_values = p[r], all_Y_values; is parsed as (all_Y_values = p[r]), all_Y_values;, which is equivalent to all_Y_values = p[r]; all_Y_values; which is equivalent to all_Y_values = p[r];. Commented Sep 18, 2015 at 11:47
  • if you want all the values into all_Y_values, make it a string and concatenate them Commented Sep 18, 2015 at 11:47
  • Or just use p, which already is an array containing all of your values. Commented Sep 18, 2015 at 11:50
  • @Vamsi Its printing "undefined" when I make all_Y_values as string Commented Sep 18, 2015 at 11:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I am able to print the values now. I want to covert these values to array. How do I do that?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.