[英]How do I sort the last names , format phone numbers, and return a string containing values from an array of objects?
我正在 JS 中解決這個玩具問題,但我已經被困在如何繼續幾個小時。
定義一個對象構造函數 People,其中包含以下值:全名、電子郵件、電話號碼、年齡和性別。
創建四個新 People(名稱和值由您決定)並將它們分配給一個數組。
- 電話號碼和年齡應該是數字。
- 至少一個全名應包含一個中間名。
然后執行以下操作:
1- 將全名值拆分為一個數組。 2- 格式化電話號碼:1(123)456-7898 3- 按姓氏排序聯系人。 4- 為每個對象創建一個字符串並將其記錄到控制台,如下所示:
先生/女士姓氏,名字| 電子郵件 | 電話號碼
a:間距應該相同並適合所有值。 | b:標題、姓名和電話號碼應左對齊。 | c: 電子郵件應該是正確的。
下面是我的代碼。 我做了一個函數,它能夠創建一個帶有名稱值的數組,將電話號碼格式化為一個數組,按姓氏對名稱數組進行排序,但我無法弄清楚將所有這些聯系起來以返回一個字符串的邏輯. 我相信它需要對性別值進行 if 聲明。 任何人都可以幫助回答這個問題的邏輯嗎? 這是我的代碼。 謝謝閱讀。
function People(name, email, age, phone, gender){
this.fullname = name;
this.email = email;
this.age = age;
this.phone = phone;
this.gender = gender;
}
// Assigning four new people obj to an array
var arr = [
new People("John Doe", "jdoe@aol.com", 32, 15555555555, "male"),
new People("Jenny Craig", "jcraig@netzero.com", 28, 19255555555, "female"),
new People("Bill Clinton", "bill.clinton@pres.gov", 59, 13105551234, "male"),
new People("George Washington Bush", "gw.bush@gmail.com", 63, 15103456432, "male")
];
// Loop through array to access each obj fullname prop to split into array.
function nmStr(arr){
var name = [];
var num = [];
arr.forEach(function(elem){
name.push(elem.fullname.split(" ").reverse());
});
name.sort();
arr.forEach(function(numb){
numb.push(numb.phone.toString().substr(0, 1) + "(" +
numb.phone.toString().substr(1, 3) + ")" +
numb.phone.toString().substr(4, 3) + "-" +
numb.phone.toString().substr(7, 4));
});
// console.log(name);
// console.log(num);
}
nmStr(arr);
好吧,我試了一下,我和你的方式有點不同,我沒有做最后的格式化,但我相信我已經做到了。 對於將其轉換為字符串的最后一步,我只是遍歷最終對象並通過將所有屬性添加在一起來創建一個字符串:
JSBin...點擊,它會自動記錄我的結果
這是我操作數組的代碼:
function phonenumbermaker(num) {
var str = num.toString();
var re = /\(?(\d{4})\)?[- ]?(\d{3})[- ]?(\d{4})/g;
var subst = '$1 $2-$3';
var result = str.replace(re, subst);
return result.substring(0, 1) + '(' + result.substring(1,4) + ')' + result.substring(4);
}
var updated = arr.map(function(person) {
var nameArray = person.fullname.split(' ');
return {
gender: (person.gender === 'male' ? 'Mr.' : 'Mrs.'),
lastname: nameArray.pop(),
restof : nameArray.join(' '),
email: person.email,
phone: phonenumbermaker(person.phone)
};
}).sort(function(a, b) {
if (a.lastname > b.lastname) return 1;
if (a.lastname < b.lastname) return -1;
return 0;
}).map(function(p) {
return p.gender + ' ' + p.lastname + ', ' + p.restof + ' | ' + p.email + ' | ' + p.phone;
});
// this part is just to log:
updated.forEach(function(finalThing){
console.log(finalThing);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.