Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Holes" in array when use es6 spread operator on string with emojis

Why when I try split string with emoji(s) using spread(...) operator I get "holes" in result array?

Example: [...'💪'] // -> ["💪", hole]

Also more emojis creates more "holes": [...'💪💪'] // -> ["💪", "💪", hole, hole]

Screenshot from Chrome v71.0.3578.98:

like image 791
gr8 Avatar asked Dec 17 '18 10:12

gr8


People also ask

How does the spread operator work in ES6?

JavaScript ES6 (ECMAScript 6) introduced the spread operator. The syntax is three dots(...) followed by the array (or iterable*). It expands the array into individual elements. So, it can be used to expand the array in a places where zero or more elements are expected.

Does spread operator work on string?

Spread syntax ( ... ) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

What does spread operator do to an array?

The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list. The rest paramter is also denoted by three dots (…). However, it packs the remaining arguments of a function into an array. The spread operator can be used to clone an iterable object or merge iterable objects into one.

Can you spread an object into an array JavaScript?

Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.


1 Answers

Certainly this is a bug.

As a workaround, Array.from() works identically except it isn't buggy.

> s="\uD83C\uDF1F\u5FCD\u8005\u306E\u653B\u6483\uD83C\uDF1F"
> [...s]
(9) ["🌟", "忍", "者", "の", "攻", "撃", "🌟", hole, hole]
> Array.from(s)
(7) ["🌟", "忍", "者", "の", "攻", "撃", "🌟"]

It looks like the fix is in Chrome 72, but you could open a bug in Chromium and ask for it to be merged to 71.

The fix and test case are here: https://crrev.com/902d21dd661033427b56d5f93c12b12339bf55ab

(I believe "hole" is V8 telling you that some native code screwed up and failed to initialize the array properly, in contrast to "empty" which can be produced by ordinary javascript.)

Yep, V8 has definitely confused itself:

> a=[...'\u{1f4a9}']
(2) ["💩", hole]
> hole=a[1]
undefined
> hole
VM384:1 Uncaught ReferenceError: hole is not defined
like image 158
Josh Lee Avatar answered Oct 18 '22 21:10

Josh Lee