所以这很奇怪,我有一个这样的foreach函数:
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 语句内的行更改为一行时:
return value;
它始终返回未定义。
对这里会发生什么有什么想法吗?
forEach 的返回将被忽略,但您可以使用 map 和过滤器:
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"
您的代码起初工作"正常",因为您正在手动更改 cookieValue
的值。
Array.prototype.forEach
不会对传递给它的回调的返回值执行任何操作。
对于这种情况,我会使用 Array.prototype.map
和 Array.prototype.reduce
的组合:
let cookieValue = cookieList.map(function(cookieItem) {
const cookieParts = cookieItem.split('=');
const value = cookieParts[1];
const key = cookieParts[0];
if (key.trim() !== cookieName) {
return null;
}
return value;
}).reduce(function(a, b) {
return a || b;
}, '');
return cookieValue;
forEach 函数中的返回值在该函数中返回。通过将返回放在外部函数中,可以在调用该函数时返回该值。请参阅此简化示例。
function x(){
function y(){
return 5 // Does not return in the x function
}
y() // = 5
return 7
}
x() // =7
你似乎正在寻找Array.find。
let cookieValue = '';
return cookieList.find(function(cookieItem) {
const cookieParts = cookieItem.split('=');
const value = cookieParts[1];
const key = cookieParts[0];
return key.trim() === cookieName
});