Assigning elements from a returned array, where the index is 1 or higher

A function is specified that returns an array with (n) elements. I want to assign these return values, but not the first.

// match returns ["abc123","abc","123"] here  
[ foo, bar ] = "abc123".match(/([a-z]*)([0-9]*)/);

Now I have

foo = "abc123"
bar = "abc"

But my intention was

foo = "abc"
bar = "123"

In other languages ​​you can do things like

//pseudocode  
[_,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);

To archive this, but how is this done in JS?

Of course one could do

[garbage,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);
garbage = undefined;

.. but, .. urgh ..

+4
source share
2 answers

I assume that you are using ES6 (ECMAScript 2015, latest version of JavaScript). If so, your pseudo-code was really close, you just do not need to have the variable name in the first position, you can simply completely abandon it:

[ , foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/);

. 1 foo 2 bar.

Live Example Babel REPL

. , , foo 0 bar 2:

// Different from what the question asks, an example
// of grabbing index 0 and index 2
[foo, , bar] = "abc123".match(/([a-z]*)([0-9]*)/);

- , .

+2

Array.prototype.slice(), .

[foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/).slice(1);

, EcmaScript 6, . , ( ).

+2

Source: https://habr.com/ru/post/1607756/


All Articles