在Javascript中定义对象的属性数组

时间:2018-03-06 02:28:39

标签: javascript arrays object defineproperty

我已经初始化了一个我希望动态添加的对象。具体来说,我想向这个对象添加对象数组。我已经尝试过以下但是都没有工作..有没有办法正确地做到这一点?最终输出应为object1.property1[0].value = 42object1.property1[0].writable = false

const object1 = {};

Object.defineProperty(object1, 'property1', '' );
object1.property1 = [{value: 42, writable: false}];


const object1 = {};
Object.defineProperty(object1, 'property1', [{value: 42, writable: false}] );

3 个答案:

答案 0 :(得分:2)

尝试使用descriptor参数中的package s; public class panelImpostazioni extends JPanel { private JComboBox comboboxLingua = new JComboBox(); static home h=new home(); public panelImpostazioni() { setBounds(140, 0, 800, 560); setLayout(null); comboboxLingua.setBounds(100, 24, 150, 45); comboboxLingua.setModel(new DefaultComboBoxModel(new String[] {"italiano", "inglese"})); add(comboboxLingua); comboboxLingua.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { h.changetext(); } }); } } 属性:

value

答案 1 :(得分:0)

对象描述符必须声明如下:

{value: [{value: 42}], writable: false}



const object1 = {};

Object.defineProperty(object1, 'property1', {value: [{value: 42}], writable: false});

console.log(object1.property1[0].value)




答案 2 :(得分:0)

由于您指定要向对象添加对象数组,因此此解决方案与其他答案类似,但应演示添加具有多个元素的数组:

const obj = {};
Object.defineProperty(obj, 'property', {
  value: [{
      value: 42,
      writable: false
    },
    {
      value: 55,
      writable: false
    }
  ]
});

console.log(obj.property[0].value);
console.log(obj.property[0].writable);

console.log(obj.property[1].value);
console.log(obj.property[1].writable);

当然,你的writable不会做任何事情,因为它将被视为另一个属性。由于您的property是一个对象数组(例如[{...},{...}]),您可能想要做的是迭代该数组并冻结这些对象:

obj.property.forEach(o=>Object.freeze(o))
obj.property[0].value=33;  // when frozen you won't be able to update the value