3

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?

Isitea
  • 741
  • 5
  • 13
  • and you probably want to know how to fix that: [Copying array by value in javascript](http://stackoverflow.com/q/7486085/218196). – Felix Kling Nov 29 '13 at 06:33

4 Answers4

2

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
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);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

you can use Array filter method like this

var res = original.filter(function(i){ return i != -1;});
Grundy
  • 13,356
  • 3
  • 35
  • 55
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/

qiu-deqing
  • 1,323
  • 7
  • 13