我是一个对象数组,我想从中获取信息(电子邮件)并将其存储到新数组中。
我已经尝试了几次,但无法完全使其发挥作用。
我最近的尝试是:
function getAllCustomerEmails(data) {
let emailArray = [];
for (let i = 0; i < data.length; i++) {
return data[i].email;
}
}
我还需要做什么/我在这里做错了什么?
我能够让所有电子邮件与控制台日志一起显示,但无法完全使其以字符串形式返回或将其保存到数组中。
最佳答案
您没有向数组推送任何内容,您必须在循环内将 email
值推送到数组,并在循环完成后返回该数组。
注意:我在这里使用对象的模拟数组,因为我不知道您的数组是什么样子。
const array = [{
userName: "name1",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a5f594f58474b43461b6a4d474b434604494547" rel="noreferrer noopener nofollow">[email protected]</a>"
},{
userName: "name2",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a6a0b6a1beb2babfe193b4beb2babffdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>"
},{
userName: "name3",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acd9dfc9dec1cdc5c09feccbc1cdc5c082cfc3c1" rel="noreferrer noopener nofollow">[email protected]</a>"
}];
function getAllCustomerEmails(data) {
let emailArray = [];
for (let i = 0; i < data.length; i++) {
emailArray.push(data[i].email);
}
return emailArray;
}
console.log(getAllCustomerEmails(array));
使用.map()的另一个选项
const array = [{
userName: "name1",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eebedfbecf3fff7f2afdef9f3fff7f2b0fdf1f3" rel="noreferrer noopener nofollow">[email protected]</a>"
},{
userName: "name2",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43363026312e222a2f7103242e222a2f6d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>"
},{
userName: "name3",
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26535543544b474f4a1566414b474f4a0845494b" rel="noreferrer noopener nofollow">[email protected]</a>"
}];
const result = array.map(x =>{
return x.email;
});
console.log(result);
关于javascript - 使用对象数组中的数据创建字符串数组的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76137733/