30
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

配列の途中に配列を挿入する JavaScript編

Last updated at Posted at 2017-06-28

まずは基本。配列と配列を結合する

    var p = [1,2,3,5];
    var p2 = [7,11,13];
    p = p.concat(p2);
    console.log(p);
    //[1,2,3,5,7,11,13]

配列の途中に配列を挿入したい

    var p = [1,2,3,5,13];
    var p2 = [7,11];
    p.splice(4,0,p2);
    console.log(p);
    //[1,2,3,5,[7,11],13] //違う、そうじゃない

こう書くと良い

    var p = [1,2,3,5,13];
    var p2 = [7,11];
    Array.prototype.splice.apply(p,[4,0].concat(p2));
    console.log(p);
    //[1,2,3,5,7,11,13]

元ネタ

How to insert an item into an array at a specific index?

spliceの仕様

Array.prototype.splice() - JavaScript | MDN

array.splice(index, howMany, [element1][, ..., elementN]);

こういう構文仕様なので、引数を配列化して、追加したい配列をconcatすれば綺麗な配列が出来るので、後はapplyすれば良いだけだった。
これ書いた人天才だね。

ちなみに

JavaScript編とか書いていますが、他の言語編を書く予定は今のところありません。

30
19
3

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
30
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?