0
0

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 3 years have passed since last update.

JavaScript 非破壊的に要素を追加した配列を生成する

Last updated at Posted at 2020-11-16

#結論
push()を使わず、スプレッド構文を使って新たな配列を生成する。
#サンプル

sample.js
let students = [['sato'], ['suzuki'], ['takahashi'], ['tanaka'], ['ito']];
//配列の各要素にインデックスの値を追加したい。e.g. ['sato'] -> ['sato', 0]

##push()

push.js
let addIndex = students.map(function(el, idx) {
 el.push(idx);
 return el;
});
console.log(addIndex); // [['sato', 0], ['suzuki', 1], ['takahashi', 2], ['tanaka', 3], ['ito', 4]] 

// 元の配列も変更されてしまう。
console.log(students); // [['sato', 0], ['suzuki', 1], ['takahashi', 2], ['tanaka', 3], ['ito', 4]]

##スプレッド構文

spread.js
let addIndex = students.map((el, idx) => [...el, idx]);
//インデックスが追加されている。
console.log(addIndex); // [['sato', 0], ['suzuki', 1], ['takahashi', 2], ['tanaka', 3], ['ito', 4]] 

// 元の配列はそのまま。
console.log(students); // [['sato'], ['suzuki'], ['takahashi'], ['tanaka'], ['ito']];

本記事の内容は別記事にて@shiracamusさんにご教授頂きました!
ありがとうございました!

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?