LoginSignup
0
1

More than 3 years have passed since last update.

ES6にある「...」は展開と残余両方あって紛らわしい

Posted at

例えば、下記のlistBは展開されるけど、listAは展開されない。

[ ...listA ] = [ ...listB ]

結果的に以下の書き方と一緒になる。

listA = [ ...listB ]

じゃあ最初の書き方は何をしてるの?と言うと残余を取っている。

const listB = [ 1, 2, 3, 4 ]
const [ a, b, ...listA ] = [ 0, ...listB ]
//a = 0, b = 1, listA = [ 2, 3, 4 ]

ここで左辺値は残余を取ると右辺値が何であれ普通の配列として代入されるようだ。
普通は気にしなくて良いが、TypedArrayなどを使用する場合は気をつけたい。
仮にTypedArrayに対して分割代入したい場合は以下のようにすると良い。

Object.assign(
  typedArray.subarray( destStart, destEnd ),
  [ ...iterable ].slice( srcStart, srcEnd )
)

Object.assign() - JavaScript | MDN

TypedArray.prototype.subarray() - JavaScript | MDN

というわけで

「...」はiterableの展開と残余の代入の両方あるから気をつけようね。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1