2014-12-06 1 views
1
var allCoords = [{ x: 2, y: 3 }, { x: 3, y: 4 }]; 
var emptySpaces = allCoords; 

emptySpaces.splice(0, 1); 
console.log(allCoords.length); 
console.log(emptySpaces.length); 

두 가지 모두 "1"을 출력하는 이유를 모르겠습니다. 원래 배열 allCoords이 수정되는 이유는 무엇입니까? emptySpaces을 편집해야하는 이유는 무엇입니까?하나의 배열을 수정하면 내가 만든 다른 하나가 수정됩니다.

+0

간단한 대답은 그들이 같은 배열되어있다. 'emptySpaces = allCoords'는 ​​복사본이 아닌 참조를 생성합니다 – charlietfl

답변

-2

은 다음과 같이 코드를 수정

(function testing() { 
    var allCoords = []; 
    var emptySpaces = allCoords.slice(); 

    emptySpaces.push({ 
     x: 1, 
     y: 2 
    }); 
    console.log(allCoords.length); 
    console.log(emptySpaces.length); 
}()); 
+0

이 예제에서'allCoords.slice()'는 단지'[]'이어야합니다. 빈 배열을 복제 할 이유가 없습니다. –

관련 문제