简体   繁体   中英

How can I port this “one-line for loop” from Python to JavaScript?

I'm not sure about the terminology used (I think it's called "lambda" or something like that), so I cannot do a proper search.

The following line in Python:

 a, b, c, d, e = [SomeFunc(x) for x in arr]

How can I do the same in Javascript?

I have this to begin with:

let [a, b, c, d, e] = arr;

But I still need to call SomeFunc on every element in arr .

A close approximation would be to use the array method map . It uses a function to perform an operation on each array element, and returns a new array of the same length.

 const add2 = (el) => el + 2; const arr = [1, 2, 3, 4, 5]; let [a, b, c, d, e] = arr.map(add2); console.log(a, b, c, d, e);

Be careful when you use array destructuring to ensure that you're destructuring the right number of elements for the returned array.

It's called .map() in JavaScript and you'd use it like this:

let arr = [1,2,3,4].map(someFunc);

and someFunc would be defined somewhere else, maybe:

function someFunc(x){ return ++x };
//or es6
let someFunc = x => ++x;

you can use map in this case

function functionF(x){return x}

let [a, b, c, d, e] = arr.map(functionF);

The term you are looking for is lambda functions .

These types of functions are ideal for quick, one-time calculations. The javascript equivalent is the map() function. For your specific case, the syntax would be

let arr = some_array.map(x => {
        return SomeFunc(x);
    });

For example, the statement

let arr = [1, 2, 8].map(num => {
        return num * 2;
    });

will assign the list [2, 4, 16] to the variable arr .

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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