繁体   English   中英

从匿名 function 调用 forEach 并将结果存储到变量

[英]Call forEach from anonymous function and store the result to variable

我需要获取一个array作为输入并存储要使用的result ,而无需创建其他函数,因为我无权访问。 所以代码一定是能得到什么result

let array = [[1,2,3,4,5,10],[1,2,3,4,5,20]];
let result = array
    .forEach(
        function(el){
            if(el[5] == 10)
            {
                return(el); //must store to variable, but this doesn't work
            }
        }
    )

我知道我错过了重点,但无法弄清楚。 我怎样才能使这项工作?

由于您只需要一些特定的元素,因此您需要对数组进行过滤

let array = [[1,2,3,4,5,10],[1,2,3,4,5,20]];
let result = array.filter((el) => el[5] == 10)

使用filter()

let result = array.filter(el => el[5] === 10);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM