LoginSignup
0
0

More than 1 year has passed since last update.

配列に要素を加える.push🍣

Posted at

.pushメソッドとは

Array.push(sth)

push() メソッドは、配列の末尾に 1 つ以上の要素を追加することができます。
また戻り値として新しい配列の要素数を返します。

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

構文 ↓

配列.push([element1[, ...[, elementN]]])

elementN
配列の末尾に追加する要素。

example

let sports = ['soccer', 'baseball']
let total = sports.push('football', 'swimming')

console.log(sports)  // ['soccer', 'baseball', 'football', 'swimming']
console.log(total)   // 4

変数sportsを後の変数totalに追加。

2つの配列をマージする

let vegetables = ['parsnip', 'potato']
let moreVegs = ['celery', 'beetroot']

// 1 つ目の配列に 2 つ目の配列をマージさせます
// vegetables.push('celery', 'beetroot'); と同じ結果になります
Array.prototype.push.apply(vegetables, moreVegs)

console.log(vegetables)  // ['parsnip', 'potato', 'celery', 'beetroot']

apply()を利用することで2つ目の配列全ての要素を1つ目の要素にマージさせている。
2 番目の配列 (例では moreVegs) が非常に大きい場合はこのメソッドを使用すべきではない。
1 つの関数が取ることのできるパラメータの最大数は実際には制限されているため。

面積の計算をしてみる

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
var areas = [];
images.forEach(function(image) {
  areas.push(image.height * image.width);
});

// 結果[300, 1800, 1728]

参考記事

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