设置值而不实例化新对象

时间:2018-12-12 22:57:06

标签: javascript

我想做的是从代码中轻松解释。

如何在不每次创建新对象的情况下获得正确的结果?

    var optionsArr = new Array();
    var labelObj = new Object();
    labelObj.label = 'Pink';
    labelObj.value = "Pink1";
    optionsArr.push(labelObj);

    labelObj.label = 'Green';
    labelObj.value = "Green2";
    optionsArr.push(labelObj);

    console.log('optionsArr' + JSON.stringify(optionsArr));

expected result :  {"label":"Pink","value":"Pink1"},{"label":"Green","value":"Green2"}


actual result :  {"label":"Green","value":"Green2"},{"label":"Green","value":"Green2"}

2 个答案:

答案 0 :(得分:0)

var obj = [];
obj[0] = {"label" : "Pink","value" : "Pink1"};
obj[1] = {"label" : "Green","value" : "Green1"};

alert(JSON.stringify(obj));

或更正确的处理数组的方法:

var obj = [];

obj.push({
  label: 'Green',
  value: 'Green2'
});

obj.push({
  label: 'Pink',
  value: 'Pink1'
});

alert(JSON.stringify(obj));

答案 1 :(得分:-1)

在JavaScript中,对象是引用类型的值,因此除了创建新对象外,没有其他方法可以传递对象值,因此您只能使用Object.assign选项。下面的方法将更改所需的属性并复制其他属性:

var optionsArr = new Array();
var labelObj = new Object();

labelObj.label = 'Pink';
labelObj.value = "Pink1";
optionsArr.push(labelObj);

// Use Object.assign() to update only some of properties
optionsArr.push(Object.assign({}, labelObj, {
  label: 'Green',
  value: 'Green2'
}));

// Original object would remain unchaged
optionsArr.push(labelObj);

console.log('optionsArr' + JSON.stringify(optionsArr));