let allLamps = [];
// Object Constructor Function that will add new obj to array
function Object (serial, type, od, ol, arc) {
this.serial = serial;
this.type = type;
this.od = od;
this.ol = ol;
this.arc = arc;
};
const obj1 = new Object(1,"g51",75,95,46);
const obj2 = new Object(2,"g38",75,95,46);
const obj3 = new Object(3,"9k",57,67,27);
function push(obj) {
allLamps.push(obj);
}
push(obj1);
push(obj2);
push(obj3);
因此,如果将数组allLamps记录到控制台,我会得到所有的 对象:
console.log(allLamps)
我想访问每个属性,如:
const getAll = allLamps.map(function(obj){
return obj.serial;
});
或
for(var i = 0; i < allLamps.length; i++){
return allLamps[i].serial;
}
但似乎我得到了不确定。注意我还在学习基础知识。我知道我做错了什么。我感谢任何解决方案。 即使我这样做:
for (var i = 0; i < allLamps.length; i++ {
return allLamps[i];
}
我只得到我的一个物体,而不是所有物体。
答案 0 :(得分:0)
字面定义数组
const lamp = (serial, type, od, ol, arc) => lamps.push({serial, type, od, ol, arc});
const lamps = [];
lamp(1,"g51",75,95,46);
lamp(2,"g38",75,95,46);
lamp(3,"9k",57,67,27);
作为推送数组项目
const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [];
lamps.push(lamp(1,"g51",75,95,46));
lamps.push(lamp(2,"g38",75,95,46));
lamps.push(lamp(3,"9k",57,67,27));
或
function Lamp (serial, type, od, ol, arc) {
this.serial = serial;
this.type = type;
this.od = od;
this.ol = ol;
this.arc = arc;
};
const allLamps = [];
lamps.push(new Lamp(1,"g51",75,95,46));
lamps.push(new Lamp(2,"g38",75,95,46));
lamps.push(new Lamp(3,"9k",57,67,27));
或
const lamp = (serial, type, od, ol, arc) => ({serial, type, od, ol, arc});
const lamps = [
[1,"g51",75,95,46],
[2,"g38",75,95,46],
[3,"9k",57,67,27]
].map(data => lamp(...data));
或
{{1}}
仅举几例