高阶函数-如何?

时间:2020-04-01 00:38:18

标签: javascript

我在javascript上还很新,因为我没有其他人要问我的问题,所以我求助于所有人。

我试图在电子邮件:password形式的数组上使用forEach方法创建一个高阶函数,而我试图使用split方法删除数组的每个字符串之间的“:”。

我将代码留在这里,以便您即时了解我的情况以及可以改进的地方。

数组:

var accounts = [
  'qewsa@mail.com:zbadaddxrl',
  'djahj@mail.com:znfdadgre', 
  'hermn@mail.com:fbppadre', 
  'erek@mail.com:trbedsastr', 
  'reey@mail.com:zvpurdsyyr', 
  'laled@mail.com:puasdsrrfr'
];

代码:

accounts.forEach(function(entry) {
    var part = entry.split(":");
    var username = part[0];
    var password = part[1];
})

1 个答案:

答案 0 :(得分:-1)

我不确定您为什么需要,但是要改善您的脚本,您可以执行以下操作:

const accounts = [ 
  'qewsa@mail.com:zbadaddxrl',
  'djahj@mail.com:znfdadgre', 
  'hermn@mail.com:fbppadre', 
  'erek@mail.com:trbedsastr', 
  'reey@mail.com:zvpurdsyyr', 
  'laled@mail.com:puasdsrrfr' 
] 

// mailAndPassword will be an array of object with the structure {username: string, password: string}

const mailAndPassword = accounts.map((entry) => {
    // Here I use destructuring to get the first and second item from the split method
    const [username, password] = entry.split(":");
    // Here I return a object with the username and password
    return {username, password}
})

console.log(mailAndPassword)

相关问题