我想將對象添加到對象數組中。如何將對象添加到javascript對象數組中
我的陣列是的jsfiddle:https://jsfiddle.net/5w4zhw92/
的預期
var sensors = [
{ id: 'led', name: 'LED', type: { port: '', path: '' } },
{ id: 'temp', name: 'TEMP', type: { path: '' } },
];
我想將對象添加到對象數組中。如何將對象添加到javascript對象數組中
我的陣列是的jsfiddle:https://jsfiddle.net/5w4zhw92/
的預期
var sensors = [
{ id: 'led', name: 'LED', type: { port: '', path: '' } },
{ id: 'temp', name: 'TEMP', type: { path: '' } },
];
它已經工作,你只需要使用it.Declare 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);
謝謝@ RE350。 –
只是改變代碼中的語句順序。首先聲明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: '' } }];
謝謝,@Gilsha。 –
它用於 –
https://jsfiddle.net/arunpjohny/5w4zhw92/2/ –
謝謝,@Arun P約翰尼拉之前定義'sensorType'。 –