Why the string split result including the "undefined"?

Hi:
I write this function to split a string.
var D = msg.payload;
var M = ;
var j = 0;
for(var i = 0; i < D.length; i++){
if(D[i]!='|')
M[j] += D[i];
else
j++;
}
msg.payload = M;
return msg;

For example, if I input 'ab|c', and I want to split the string to two values without '|', the output results are:
array[2]

0: "undefinedab"

1: "undefinedc"
The result is almost correct but just including the 'undefined'. Why?

You want to add D[i] to the array, but you are concatenating += instead.
Shouldn't you use M[j].push(D[i]) instead ?

Note that there is a split node to do this stuff.

1 Like

The reason is that the line
M[j] += D[i];
is the same as
M[j] = M[j] + D[i];
so consider what happens the first time through. This is
M[0] = M[0] + "a";
but as initially M[0] is undefined the result is "undefineda".
You need to change

j++

to

j++
M[j] = ""

so that it is initialised to an empty string. However, as @bakman2 said there is a Split node that will do this for you.

1 Like

In fact (as @zenofmud has pointed out to me) my solution is not quite correct, because the j++ is in an else block, but is not surrounded by braces, it is necessary to include the braces. Personally I never write code like

if (A) 
  B;
else
  C;

I would always write

If (A) {
  B;
} else {
  C;
}

because I have seen bugs introduced so many times when an additional line is inserted into the if or else clause.
In addition it is necessary to initialise M[0] at the start. So a working version of the function is

var D = msg.payload;
var M = [];
var j = 0;
M[j] = '';  // < initialise M[0]
for(var i = 0; i < D.length; i++){
    if(D[i]!='|') {
        M[j] += D[i];
    } else{
        j++;
        M[j] = ''; // < initialise M[j]
    }
}
msg.payload = M;
return msg;

As before, though, a Split node will do the job with much less effort.