我很难找到以有条理的方式进行输出显示的方法。如何根据图片更改输出以使其显示?
我的代码
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Wang",
number: "0000000001",
nationality: "Australian",
address: ['Street','Microsoft','California','SL','98052']
};
friends.steve = {
firstName: "Steve",
lastName: "Wozniak",
number: "0021221312",
nationality: "American",
address: ['Street','Apple','California','SL','98052']
};
var list = function(obj){
for(var check in obj){
console.log(check);
}
};
var search = function(name){
for(var prop in friends){
if(friends[prop].firstName === name) {
console.log(friends[prop]);
return friends[prop];
}
}
};
list(friends);
search("Bill");
答案 0 :(得分:0)
我会编写一个函数而不是直接使用console.log。 类似的东西:
var logFriend = function(friend){
console.log("First Name: " + friend. firstName);
console.log("Last Name: " + friend. lastName);
console.log("Number: (" + friend.number.substring(0, 2) + ") " + friend.number.substring(3, 9));
}
答案 1 :(得分:0)
直接将对象记录到控制台,将根据浏览器的内置机制进行记录。每个浏览器都会以自己的方式输出对象,因此如果您希望它看起来漂亮,您需要创建一个自定义函数,您可以根据需要打印所有内容。
您可以使用扩展方法PrintFriend()
创建名为“Friend”的类,您可以在其中输出所有相关信息,并从中实例化您的朋友:
var friends = {};
//this is our class declaration
var Friend = function (firstName, lastName, number, nationality, address) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.nationality = nationality;
this.address = address;
};
//a prototype function that will be available to all objects of
//class 'Friend'
Friend.prototype.PrintFriend = function () {
console.log("First Name: " + this.firstName);
console.log("Last Name: " + this.lastName);
console.log("Number: " + this.number);
console.log("Address: " + this.address.join().replace(/,/g," "));
document.body.innerHTML+="First Name: " + this.firstName+"<br/>";
document.body.innerHTML+="Last Name: " + this.lastName+"<br/>";
document.body.innerHTML+="Number: " + this.number+"<br/>";
document.body.innerHTML+="Address: " + this.address.join().replace(/,/g," ")+"<br/>";
};
//we add an object named 'bill' to the friends array, the object will
//be instantiated from the Friend class
friends["bill"] = new Friend(
"Bill",
"Wang",
"0000000001",
"Australian", ['Street', 'Microsoft', 'California', 'SL', '98052']);
//same with steve
friends["steve"] = new Friend(
"Steve",
"Wozniak",
"0021221312",
"American", ['Street', 'Apple', 'California', 'SL', '98052']);
var list = function (obj) {
for (var check in obj) {
console.log(check);
}
};
//we call the custom function print friend here
var search = function (name) {
for (var prop in friends) {
if (friends[prop].firstName === name) {
friends[prop].PrintFriend();
return friends[prop];
}
}
};
list(friends);
search("Bill");