forEach在没有条件的情况下返回值

时间:2018-02-20 08:37:48

标签: javascript arrays foreach

我有这个数组,我循环遍历它,我只是想让它返回数组的元素而没有任何条件我在forEach循环的一些例子中看到只有在满足某个条件时返回的东西。 这是我的代码:

let tickets = ['Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A18',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A3',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1']

let ticket = tickets.forEach(ticket => {
    return ticket
});
 console.log(ticket); // undefined why?

3 个答案:

答案 0 :(得分:0)

来自developer.mozilla.org

  

forEach()为每个数组元素执行一次回调函数;   与map()或reduce()不同,它总是返回undefined值而且是   不可链接。典型的用例是执行副作用   链的一端。

答案 1 :(得分:0)

我不完全确定你想要完成什么。但是如果需要在一个tickets中合并所有string元素,请输入以下代码:

let resultString = "";
tickets.map(singleTicket => {
    resultString += singleTicket + " ";
});

答案 2 :(得分:0)

forEach没有返回任何内容,您需要使用地图而不是像

一样



let tickets = ['Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A18',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A3',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1',
'Follow link to download your ticket https://ticketsoko.nouveta.co.ke/ticket.html?ticket_number=201711297A1']

let ticket = tickets.map(ticket => {
    return ticket
});
console.log(ticket);




return内的

forEach就像一个continue语句,推迟执行后面的语句并执行下一次迭代。

但是如果你想简单地想要返回数组的所有元素,那么你也可以不使用任何东西而只使用原始数组