Str.split (''). Map () vs arr.map (), for fixed input

It is curious if there is any use to choosing one of these approaches over the other. Here is an illustration.

'one two'.split(' ').map(string => doSomething(string)); 

vs

 ['one', 'two'].map(string => doSomething(string)); 

I saw the first approach in several popular front-end libraries, but the second makes sense to me when reading code quickly. Is this just a style choice? Or is there some kind of obscure advantage to splitting a line string over simple mapping through an array?

+5
source share
2 answers

['one', 'two'] is the result of 'one two'.split(' ') , so no difference.

String.prototype.split() :

The split() method split() String object into an array of strings, dividing the string into substrings.

-1
source

The only difference is readability (and for some people it might also be easier to introduce).

Some people find 'one two'.split(' ') more readable than the JavaScript notation in an array.

If you are used to JSON, you think the second is more readable, since it is more clear what will happen. (And his tick is faster!)

Other languages ​​are even built into the language. In Ruby, for example, you can write %w(one two) by creating an array with the strings one and two.

-1
source

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


All Articles