LoginSignup
0
1

More than 3 years have passed since last update.

JavaScript~配列の基本

Posted at

JavaScript~配列の基本

コピペして使ってください。
ES6を対象としています。

配列に追加(pushメソッド)

sample.js
//配列の定義
const characters = ["a", "b", "c"];
// pushメソッドを使って配列の最後尾に追加
characters.push("d");

配列の繰り返し処理(forEachメソッド)

sample.js
//配列の定義
const characters = ["a", "b", "c"];
// forEachメソッドを使って、配列charactersの中身をすべて出力
characters.forEach((character)=>{
  console.log(character);
});

条件にあう1つ目の要素を取り出す(findメソッド)

sample.js
//配列の定義
const numbers = [1, 3, 5, 7, 9];

// findメソッドを使って3の倍数を見つける
const foundNumber = numbers.find((number)=>{
  return number%3===0;
});
console.log(foundNumber);

条件にあう全ての要素を取り出す(filterメソッド)

sample.js
//配列の定義
const characters = [
  {id: 1, age: 14},
  {id: 2, age: 5},
  {id: 3, age: 100}
];

// charactersから20歳未満を取り出す
const underTwenty = characters.filter((character)=>{
  return character.age<20;
});
console.log(underTwenty);

新しい配列をつくる(mapメソッド)

sample.js
//配列の定義
const names = [
  {firstName: "Kate", lastName: "Jones"},
    {firstName: "John", lastName: "Smith"},
    {firstName: "Denis", lastName: "Williams"},
    {firstName: "David", lastName: "Black"}
];

// 定数namesにmapメソッドを使って新しい配列を作る
const fullNames = names.map((name)=>{
  return name.firstName + name.lastName;
});
console.log(fullNames);
0
1
1

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