0

This is my code and it gets options from a jsTree checkbox tree list:

var level1, r = [];

for (i = 0, j = data.selected.length; i < j; i++) {
    r[0] = data.instance.get_node(data.selected[i]).text.trim();
    r[1] = data.instance.get_node(data.selected[i]).parents.length;

    if(r[1] == 1) {
       level1 += r[0] + ", ";
       alert(level1);
    }
}

The alert of the above contains undefined along with the correct choices from the checkboxes. Any idea why I am getting undefined in the output?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Homer_J
  • 3,277
  • 12
  • 45
  • 65

2 Answers2

1

The problem is that level1 is undefined when you first try to use it here:

level1 += r[0]+", ";

That's the same as:

level1 = level1 + r[0]+", ";

The problem is level1 undefined the first iteration through and so the text contains undefined and concatenating it concatenates "undefined" as a string as it is coerced. Initialize it to an empty string:

var level1 = "";

That way it will not be undefined when you access it.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
0

This

var level1, r = [];

for (i = 0, j = data.selected.length; i < j; i++) {
    r[0] = data.instance.get_node(data.selected[i]).text.trim();
    r[1] = data.instance.get_node(data.selected[i]).parents.length;

    if(r[1] == 1){
       level1 += r[0]+", ";
       alert(level1);
    }
}

Should be

var level1 = '';
   //Or leve1 = []; If you really need it as an array.
var r = [];

for (i = 0, j = data.selected.length; i < j; i++) {
    r[0] = data.instance.get_node(data.selected[i]).text.trim();
    r[1] = data.instance.get_node(data.selected[i]).parents.length;

    if(r[1] === 1){
       // level1[0] += r[0]+", "; If array.
       level1 += r[0]+", ";
       alert(level1);
      // alert(level1[0]); If array.
    }
}

The level1 is undefined since level1, r = [] makes r === [] and level1 === undefined.

So I suggest you explicitly declare both variables as shown in the code block above.

Also I fixed comparison operators, see here why

Community
  • 1
  • 1
ArchNoob
  • 3,946
  • 5
  • 32
  • 59
  • Thanks ArchNoob - appreciated. String was indeed the issue but, as it happens, the above solves a different issue I was facing elsewhere! – Homer_J May 08 '17 at 16:56
  • Awesome! @Homer_J – ArchNoob May 08 '17 at 17:07
  • "Is an array since you declared it as ..." - where do you see that? They explicitly concatenate a string so it's probably a string – Andrew Li May 08 '17 at 17:13
  • @AndrewLi Ahh, you are right. I mistakenly thought `var some, some1 = []` makes both some & some1 === []. But it actually makes some === undefined and some1 === []. I updated the answer to fit the corrections. Thanks! – ArchNoob May 08 '17 at 17:46