0

我正在寻找一种方法将这两个对象组合成一个函数或减少我的行数的东西。

var fsInfo1 = {
    name: 'Joshua Velez',
    address:{
        street: '94-1411 Kulewa Loop ',
        city: 'Waipahu, ',
        state: 'HI'
    },
    gpa: [3.3,4.0,2.8]

}
var fsInfo2= {
    name: 'John Doe',
    address:{
        street: 'Some Street ',
        city: 'Wahiawa, ',
        state: 'HI'
    },
    gpa: [3.4,3.6,3.1]
}

console.log("名称:" + fsInfo1.name)

console.log("地址:" + fsInfo1.address['street'] + fsInfo1.address['city'] + fsInfo1.address['state']) console.log("GPA:" + fsInfo1.gpa[0 ],fsInfo1.gpa[1],fsInfo1.gpa[2])

console.log("名称:" + fsInfo2.name)

console.log("地址:" + fsInfo2.address['street'] + fsInfo2.address['city'] + > fsInfo2.address['state']) console.log("GPA:" + fsInfo2.gpa[ 0],fsInfo2.gpa[1],fsInfo2.gpa[2])

4

2 回答 2

1

一种方法是:

var fsInfo1 = // same as before
var fsInfo2 = // same 
function logFsInfo(fsInfo) {
    console.log("Name "+fsInfo.name);
    console.log("Address "+fsInfo.address.street + fsInfo.address.city + fsInfo.address.state);
    console.log("GPA "+fsInfo.gpa.join(",")); //combine gpa values into a string separated by commas
}
logFsInfo(fsInfo1);
logFsInfo(fsInfo2);

但这真的取决于你想在这里做什么。您所做的只是打印 fsInfo 数据吗?如果是这样,当然,只需执行类似的操作作为打印该数据的快捷方式。但是,如果您想开始使用 fsInfo 对象做其他事情,我建议您创建一个类并将方法附加到它。但是,对于简单的使用来说,这完全是矫枉过正。

于 2013-10-12T06:17:12.560 回答
0
var fsInfo1 = {
    name: 'Joshua Velez',
    address:{
        street: '94-1411 Kulewa Loop ',
        city: 'Waipahu, ',
        state: 'HI'
    },
    gpa: [3.3,4.0,2.8]

}
var fsInfo2= {
    name: 'John Doe',
    address:{
        street: 'Some Street ',
        city: 'Wahiawa, ',
        state: 'HI'
    },
    gpa: [3.4,3.6,3.1]
}
var obj = new Object();

obj[0] = fsInfo1;
obj[1] = fsInfo2;
var count = Object.keys(myArray).length;
for(i=0 ; i<count;i++)
{
      console.log("Name: " + obj[i].name)

console.log("Address: " + obj[i].address['street'] + obj[i].address['city'] + obj[i].address['state']) console.log("GPA: " + obj[i].gpa[0],obj[i].gpa[1],obj[i].gpa[2])
}
于 2013-10-12T06:10:25.777 回答