foreach 内部的返回值 [英] return value inside foreach
本文介绍了foreach 内部的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以这很奇怪,我有一个这样的 foreach 函数:
So this is very weird, I have a foreach function like this:
let cookieValue = '';
cookieList.forEach(function(cookieItem) {
const cookieParts = cookieItem.split('=');
const value = cookieParts[1];
const key = cookieParts[0];
if (key.trim() === cookieName) {
cookieValue = value;
return cookieValue;
}
});
return cookieValue;
工作正常,但是当我将 if 语句中的行更改为一行时:
which works fine, however when I change the lines inside the if statement to a single line:
return value;
它总是返回 undefined.
It returns undefined always.
对这里可能发生的事情有什么想法吗?
Any ideas of what can be happening here?
推荐答案
forEach 的返回被忽略,但你可以使用 map 和 filter:
The return of forEach is ignored but you can use map and filter:
function getCookieValue(cookieList, cookieName) {
var val = cookieList.map(function(cookieItem) {
var cookieParts = cookieItem.split('=');
var value = cookieParts[1];
var key = cookieParts[0];
return (key.trim() === cookieName) ? value : null;
})
.filter((value) => { return value != null })[0];
return val;
}
let cookieValue = getCookieValue(["key1=val1", "key2=val2"], "key2"); // > "val2"
这篇关于foreach 内部的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文