[英]How to add Object to the array of object in javascript
我想將對象添加到對象數組。
我的數組在jsfiddle中: https ://jsfiddle.net/5w4zhw92/
預期的
var sensors = [
{ id: 'led', name: 'LED', type: { port: '', path: '' } },
{ id: 'temp', name: 'TEMP', type: { path: '' } },
];
它已經在工作,您只需要在使用變量之前聲明該變量即可。先聲明sensorType
然后再使用它。
var sensorType = {
sender: {
port: '',
path: ''
},
receiver: {
path: ''
}
};
var sensors = [
{ id: 'led', name: 'LED', type: sensorType.sender },
{ id: 'temp', name: 'TEMP', type: sensorType.receiver }
];
console.log(sensorType.sender);
console.log(sensors);
只需更改代碼中語句的順序即可。 首先聲明sensorType對象。
var sensorType = { sender: { port: '', path: '' }, receiver: { path: '' } }; var sensors = [ { id: 'led', name: 'LED', type: sensorType.sender }, { id: 'temp', name: 'TEMP', type: sensorType.receiver }, ]; console.log(sensorType.sender); //Returns Object {port: "", path: ""} console.log(sensors); //[{ id: 'led', name: 'LED', type: { port: '', path: '' } },{ id: 'temp', name: 'TEMP', type: { path: '' } }];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.