6
4

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.

JSのpush()について

Posted at

JSのpush()について

初心者がJSのpush()についてメモしています。

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」の返り値について

var items = [1,2,3,4];
var result = items.push();
console.log(result);
  • 連想配列では「push」を使えない
  • 「push」はあくまで配列の組み込みメソッド
  • 「push」を使って、配列の中に別の配列を追加するのは特に問題ない
var obj = { name:'太郎', age:30 };
obj.push( ['花子', 28] );
console.log( obj );

実行結果

Uncaught TypeError: obj.push is not a function
  • 連想配列に要素を追加するには、まだ連想配列にないキー文字列を指定して値を代入します。疑似コードは以下
arr[キー配列] = //keyとvalueをセットする
  • しかし、配列の中にオブジェクトを追加することは可能
    連想配列に配列を pushはだめ、
    配列にオブジェクトを pushは OK

var items = [1,2,3,4];
items.push({one:1,two:2,three:3});
console.log(items);

「pop」は配列の末尾のデータを削除する

pop.js

var array = [1,2,3,4,5];
array.pop();
console.log(array);
[1,2,3,4]

concatメソッドで結合


var array1 = ['aaa','bbb'];
var array2 = ['ccc','ddd'];
var result = array1.concat(array2);

console.log(result);
6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?