2017-01-07 6 views
0
var brand = [{id:1,name:'samsung',price:1000},{id:1,name:'lg',price:2000}]; 
var changed = brand[0].price = 2000; 

지금은 삼성의 가격이 2000과 같고 변경되었지만 변경되지 않고 브랜드 변수를 변경하는 방법은 무엇입니까?객체 값을 변경하는 불변 함수

또는 어쩌면 내가 redux에 불변의 개념을 오해 한 것일까 요? 위의 코드는 실제로 괜찮습니까?

+0

당신이 묻는 바는 분명하지 않습니다. 즉, 표시된 컨텍스트에서 개체를 돌연변이시키는 데 아무런 문제가 없습니다. –

+0

@DaveNewton - 컨텍스트는'redux' 태그입니다. –

+0

@OriDrori 이는 상황이 불충분합니다. '브랜드'로 수행되는 작업은 상황을 결정하고 불변성이 중요한지 아닌지를 결정합니다. 즉, 실제 상황없이 X-Y 문제 일 수 있습니다. –

답변

0

Object#assign을 사용하여 필요한 변경 사항으로 새 개체를 만듭니다. Array#slice을 사용하면 원래 배열에서 변경되지 않은 항목을 가져오고 Array#concat을 사용하여 원본을 변경하는 대신 새 배열을 만들 수 있습니다. 당신은 코드 또는 브라우저 호환성이 문제가되지 않을 transpile 경우

var brand = [{id:1,name:'samsung',price:1000},{id:1,name:'lg',price:2000}]; 
 

 
var index = 0; // changed element index 
 

 
// creates a new object with the merge properties 
 
var item = Object.assign({}, brand[index], { price: 2000 }); 
 

 
// creates a new array by combining the elements before the changed item, with the changed item, and the elements after the it in the right order 
 
var changed = brand.slice(0, index) // the items before the changed item 
 
    .concat(
 
    item, // the changed item 
 
    brand.slice(index + 1) // the elements after the changed item 
 
); 
 

 
console.log(changed); 
 
console.log(brand); // brand haven't changed

, 당신은 array spreadobject spread 구문을 사용할 수 있습니다 :이 좋은를

const brand = [{id:1,name:'samsung',price:1000},{id:1,name:'lg',price:2000}]; 
 

 
const index = 0; // changed element index 
 

 
const changed = [ 
 
    ...brand.slice(0, index), // the elements before the changed item 
 
    { ...brand[index], price: 2000 }, // the changed item 
 
    ...brand.slice(index + 1) // the items after the changed items 
 
]; 
 

 
console.log(changed); 
 
console.log(brand); // brand haven't changed

+0

[item]이 (가) es2015입니까? 전에 그 구문을 본 적이 없어요. immutable 프로그래밍과 관련이있는 push()입니까? 나는 밀기보다 concat을 보았다. –

+0

'Object.assign'은 es2015입니다. 나머지는 일반 ES5입니다. –

+0

Push는 배열을 변경하고 concat은 새로운 배열을 만듭니다. –