2

I need to create an array from tree elements in Javascript and being a newbie I don't know how to achieve this.

pseudo-code :

function make_array_of_tree_node(tree_node)
{
   for (var i = 0; i < tree_node.childCount; i ++) {
      var node = tree_node_node.getChild(i);
      if (node.type ==0) {
         // Here I'd like to put a link (node.title) in an array as an element
      } else if (node.type ==6) {
         // Here the element is a folder so a I need to browse it
         make_array_of_tree_node(node)
      }
   }
}

// Some code
make_array_of_tree_node(rootNode);
// Here I'd like to have access to the array containing all the elements node.title
2
  • 1
    Your for loop is missing a close }. Commented Jun 6, 2011 at 13:25
  • @Mike Samuel A typo in SO, thank you for noticing it :-) Commented Jun 6, 2011 at 14:03

1 Answer 1

2

You can declare an array like this:

var nodes = [];

Then you can add things to it with:

nodes.push(something);

That adds to the end of the array; in that sense it's kind-of like a list. You can access elements by numeric indexes, starting with zero. The length of the array is maintained for you:

var len = nodes.length;

What you'll probably want to do is make the array another parameter of your function.

edit — To illustrate the pattern, if you've got a recursive function:

function recursive(data, array) {
  if ( timeToStop ) {
    array.push( data.whatever );
  }
  else {
    recursive(data.subData, array);
  }
}

Then you can use a second function to be the real API that other code will use:

function actual(data) {
  var array = [];
  recursive(data, array); // fills up the array
  return array;
}

In JavaScript, furthermore, it's common to place the "recursive" function inside the "actual" function, which makes the recursive part private and keeps the global namespace cleaner.

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

3 Comments

You can also add something to an array in JS with nodes[nodes.length] = theItem
But declaring the array in the function is going to erase the previous one, no ?
Yes - that's why I said you should make the array a parameter to the function. When you call the function, pass in the array. A common pattern is to wrap your function in an "outer" function. I'll update my answer ...

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.