本文介绍了返回值在foreach里面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
let cookieValue ='';这是一个非常奇怪的事情,我有一个像这样的foreach函数:
cookieList.forEach(function(cookieItem){
const cookieParts = cookieItem.split('=');
const value = cookieParts [1];
const key = cookieParts [0];
if(key.trim()=== cookieName){
cookieValue = value;
return cookieValue;
}
}) ;
返回cookieValue;
可以正常工作,但是当我将if语句中的行更改为单行时: p>
返回值;
它始终返回undefined
有什么想法可以在这里发生?
解决方案
返回的forEach被忽略,但你可以使用映射和过滤器: 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];
返回val;
let cookieValue = getCookieValue([key1 = val1,key2 = val2],key2); //> val2
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;
which works fine, however when I change the lines inside the if statement to a single line:
return value;
It returns undefined always.
Any ideas of what can be happening here?
解决方案
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里面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!