JavaScript

配列とオブジェクト

複数の値や、関連する項目をまとめて扱いましょう。

JavaScript入門の講座一覧

01

配列の基本

配列の番号は0から始まります。pushで末尾へ追加し、lengthで要素数を調べられます。

配列を操作するJAVASCRIPT
const fruits = ['りんご', 'みかん', 'ぶどう'];
fruits.push('もも');
console.log(fruits[0]);
console.log(fruits.length);
実行結果OUTPUT
りんご
4
02

mapとfilter

mapは各要素を変換し、filterは条件に合う要素を抽出します。

合格者を抽出するJAVASCRIPT
const scores = [72, 95, 48, 81];
const passed = scores.filter((score) => score >= 60);
const doubled = passed.map((score) => score * 2);
console.log(passed);  // [72, 95, 81]
console.log(doubled); // [144, 190, 162]
03

オブジェクト

オブジェクトは、プロパティ名と値の組み合わせで利用者や商品などを表します。

利用者データJAVASCRIPT
const user = {
    name: 'Mity',
    age: 20,
    introduce() {
        return `${this.name}です`;
    }
};
console.log(user.introduce()); // Mityです
04

分割代入

分割代入を使うと、配列やオブジェクトの値を短く取り出せます。

プロパティを取り出すJAVASCRIPT
const product = { name: 'ノート', price: 300 };
const { name, price } = product;
console.log(`${name}: ${price}円`); // ノート: 300円