[Lab] Javascript 大小事試試 --- object function array綜合練習1
這裡就不囉嗦,直接放code做個記錄。
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};
var contacts = [bob, mary];
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}
function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}
/*Create a search function
then call it passing "Jones"*/
function search(lastName) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if(contacts[i].lastName == lastName)
printPerson(contacts[i]);
}
}
function add(firstName, lastName, email, phoneNumber){
var contactsLength = contacts.length;
var temp = Object();
/*
temp.firstName = firstName;
temp.lastName = lastName;
temp.email = email;
temp.phoneNumber = phoneNumber;
contacts[contacts.length] = temp;
*/
contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
}
}
add("tao","chen","ggg","0921192337");
search("chen");
---------------------------------------------
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};
var contacts = [bob, mary];
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}
function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}
/*Create a search function
then call it passing "Jones"*/
function search(lastName) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if(contacts[i].lastName == lastName)
printPerson(contacts[i]);
}
}
function add(firstName, lastName, email, phoneNumber){
var contactsLength = contacts.length;
var temp = Object();
/*
temp.firstName = firstName;
temp.lastName = lastName;
temp.email = email;
temp.phoneNumber = phoneNumber;
contacts[contacts.length] = temp;
*/
contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
}
}
add("tao","chen","ggg","0921192337");
search("chen");
---------------------------------------------
使用 constructor時要記得寫 new
在object裏面的function使用this來access自己的property
留言
張貼留言