Question

I made a code that removes '-1' in array, but I don't want to modify original one.

following is that one.

var original = [ 1, 2, 3, 4, -1, -1 ];
var temp = original;
for ( var i = ( temp.length - 1 ); i >= 0; i-- ) {
    if ( temp[j] == -1 ) {
    temp.splice( i, 1 );
}

after script executed. original is [ 1, 2, 3, 4 ] and temp also is [ 1, 2, 3, 4 ]

both original and temp are modified!

why is it?

Was it helpful?

Solution

That is because there is only one array - simply, both variables name the same array. Just like a person (with nicknames), a single object can have many names.

The = (assignment) operator in JavaScript does not copy/clone/duplicate the object being assigned.

The Array.splice function mutates the array (of which there is only one) which, when taken with the above, explains the behavior.

To create a shallow clone of an array, arr.slice(0) can be useful.

OTHER TIPS

you can use Array filter method like this

var res = original.filter(function(i){ return i != -1;});

This is because you are using only one array.

var temp = original;

Also to mention that the equal= operator does not copy the object.

You can try something like this to achieve what you want:

var temp = original.slice(0);
var original = [ 1, 2, 3, 4, -1, -1 ];

var tem = original.filter(function (d) {
    return d !== -1;
});

console.log(original); // [1, 2, 3, 4, -1, -1] 
console.log(tem); // [1, 2, 3, 4] 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

demo: http://jsfiddle.net/J37tF/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top