● 我们以上述的这个账号来举例子,这个用户名就是缩写stw
const user = 'Steven Thomas Williams';
const username = user
.toLowerCase()
.split(' ')
.map(function (name) {
return name[0];
})
.join('');
console.log(username);
● 为了精简代码,我们将上述代码改写为箭头函数
const user = 'Steven Thomas Williams';
const username = user
.toLowerCase()
.split(' ')
// .map(function (name) {
// return name[0];
.map(name => name[0])
.join('');
console.log(username);
● 但是这个只能将一个名字生成出来,为了方便,我们将这个功能写成一个函数,将名字传入的话,就能实现还能生成用户名
const createUsernames = function (user) {
const username = user
.toLowerCase()
.split(' ')
.map(name => name[0])
.join('');
return username;
};
console.log(createUsernames('Steven Thomas Williams'));
● 但是现在我们只能一个一个传参数,现在我们想要传入多个账号来生成用户名
const createUsernames = function (accs) { //定义一个名为createUsernames的函数,可以传入一个数组
accs.forEach(function (acc) { //利用forEach循环数组
acc.username = acc.owner //为数组添加一个key为username的参数,值为owner参数经过小写、分片、取首字母、组合之后的值
.toLowerCase()
.split(' ')
.map(name => name[0])
.join('');
});
};
createUsernames(accounts); //将数组传入函数中
console.log(accounts); //将添加username参数的数组打印到控制台