Let's try to understand what happens.
- A string is defined with 5 letters in, separated by semi-colons.
- An array is created, data3.
- An array is created by splitting the string. So, the array will contain:
code:
[a,b,c,d,e,f]
- A copy of this array is stored as data2.
- data3 is filled with the first 5 elements of the data array.
- The content of data is changed.
The error is that when you assign an array variable to a new variable, it is dependent of this original array. That is, when you change the original one, the new one follows. When you change the second array, it becomes independent and will inherit all elements from the first array. After that, you can change both independently.
So, to make the data2 variable independent, you can use a nifty trick to make it immediately inherit the elements from the original array instead of making a reference to the first one:
code:
...
var data = str.split(';');
var data2 = data.slice(0);
for(var i = 0;i<=5;i++){
...
A small explanation here: the slice function returns a selected amount of elements from an array. You can specify a start and end position, but when you leave out the end parameter, it'll return the elements from the given start position to the end or the array. Result: all elements will be returned as a new array, and this returned array is saved as data2 variable.
Oh note: you may want to remove the final semi-colon after "f" in your string, as you have an empty element at the end of your arrays now.
Reference: http://www.sematopia.com/?p=12