return value inside foreach

后端 未结 3 1929
猫巷女王i
猫巷女王i 2020-12-12 05:49

So this is very weird, I have a foreach function like this:

  let cookieValue = \'\';

  cookieList.forEach(function(cookieItem) {
    const cookieParts = co         


        
3条回答
  •  情歌与酒
    2020-12-12 06:14

    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"
    

提交回复
热议问题