変数と定数
/**
* var : グローバルスコープ、寿命の問題あり、競合しやすい
* let :値を変更可能
* const :変更不可
*/
let userAge = 25;
console.log(userAge);
userAge = 26;
console.log(userAge);
const fixedAge = 18;
console.log(fixedAge);
// エラー:constは変更不可
// fixedAge = 20;
// エラー:初期化必須
// const emptyAge;
データ型
/**
* String
* Number
* Boolean
* null
* undefined
*/
// 文字列
const userName = "Taro";
const nickName = 'Taro_001';
// 数値
const age = 25;
const rating = 4.5;
// 真偽値
const isValid = true;
// null(undefinedではなく、明示的にnullとして定義)
const emptyValue = null;
// undefined
let undefinedValue;
const undefinedValue2 = undefined;
console.log(typeof rating);
console.log(typeof emptyValue); // nullはobjectと表示
console.log(typeof undefinedValue);
文字列操作
テンプレート文字列
const name = "Yamada";
const years = 22;
// 連結
console.log("My name is " + name + " and I am " + years);
// テンプレート文字列
console.log(`My name is ${name} and I am ${years}`);
文字列の主なメソッド
const text = "Hello JavaScript!";
// lengthプロパティ
console.log(text.length);
// 大文字変換
console.log(text.toUpperCase());
// 小文字変換
console.log(text.toLowerCase());
// 部分文字列取得、開始と終了index、0から開始、左閉右開区間
console.log(text.substring(0, 5));
// 文字列分割、文字配列に分割、引数が文字列の場合は引数で分割、空文字の場合は文字ごとに分割
console.log(text.split(""));
console.log(text.split("S"));
console.log(text.split("Ja"));
配列
const numArray = new Array(1, 2, 3, 4, 5);
console.log(numArray);
const strArray = new Array("X", "y", "5", "ZZ", "F");
console.log(strArray);
// この定義方法も可能、コンストラクタと同じ
const boolArray = [true, false, false, true, null];
console.log(boolArray);
// 配列要素の型は異なっても可
const mixedArray = new Array(1, 3.3, "DD", true, null, undefined);
console.log(mixedArray);
console.log(mixedArray[1]); // インデックスで要素アクセス
mixedArray[2] = "DDD"; // 要素変更
// mixedArray = []; // エラー、配列オブジェクト自体はconst、配列自体は変更不可、要素のみ変更可能
mixedArray.push("末尾追加"); // 末尾追加
mixedArray.unshift("先頭挿入"); // 先頭挿入
console.log(mixedArray);
mixedArray.pop(); // 末尾削除
console.log(mixedArray);
console.log(Array.isArray(mixedArray)); // Array静的メソッド、配列か判定
// 要素インデックス取得、要素がない場合は-1
console.log(mixedArray.indexOf("DDD"));
console.log(mixedArray.indexOf("DD"));
// 配列拡張
let largeArray = [1, 2, 3, 4];
console.log(largeArray);
largeArray[8] = 9; // サイズ拡大と代入
console.log(largeArray);
// ソート
let sortArray = [7, 3, 1, 8, 6];
sortArray.sort();
console.log(sortArray);
オブジェクト
const employee = {
firstName: "Sato",
yearsOld: 22,
interests: ["reading", "gaming", "traveling"],
location: {
street: "123 central ave",
city:"Tokyo",
prefecture:"Tokyo",
},
};
console.log(employee);
console.log(employee.firstName);
console.log(employee.interests[1]);
console.log(employee.location.city);
employee.street = "125 central ave" // プロパティ変更
employee.email = "s.sato@example.com" // 新規プロパティ追加
console.log(employee);
// 分割代入、オブジェクトから複数の内容をコピー
const { firstName, yearsOld, location: { city } } = employee;
console.log(firstName);
console.log(yearsOld);
// エラー : 本質的に抽出されるのはcity、対応関係はemployee.location.city
// console.log(location); // エラー
// console.log(location.city); // エラー
console.log(city);
オブジェクト配列とJSON
const tasks = [
{
taskId: 1,
description: "ゴミ出し",
completed: true,
},
{
taskId: 2,
description: "上司との打ち合わせ",
completed: true,
},
{
taskId: 3,
description: "歯医者の予約",
completed: false,
},
];
console.log(tasks[1].description); // インデックスで値取得
// 追加・削除・変更・検索の詳細は省略、本質的には配列
const taskJSON = JSON.stringify(tasks); // JSONに変換
console.log(taskJSON);
条件分岐と三項演算子
条件分岐
const a = "10";
const b = 11;
const c = 5;
// === 値と型を比較、 == と > 、 < は値のみ比較
if (a === 10) {
console.log("a === 10");
}
if (a !== 10) {
console.log("a !== 10");
}
if (a == 10) {
console.log("a == 10");
}
if (a != 10) {
console.log("a != 10");
}
if (a > 5) {
console.log("a > 5");
}
// 論理和と論理積
if (b > 10 || c > 10) {
console.log("b > 10 || c > 10");
}
if (b > 10 && c > 10) {
console.log("b > 10 && c > 10");
}
三項演算子
const conditionA = true;
const conditionB = false;
const conditionC = true;
const conditionD = false;
console.log( conditionB ? "BBB" : (conditionD ? "DDD" : (conditionC ? "CCC" : conditionA)));
switch文
const selectedColor = "blue";
switch (selectedColor) {
case "red":
console.log("red");
break;
case "blue":
case "black":
console.log("blue or black");
break;
case "yellow":
console.log("yellow");
break;
default:
console.log("other");
break;
}
ループ処理
forループ
for (let counter = 0; counter < 10; ++counter) {
console.log(`for loop count: ${counter}`);
}
forin(オブジェクトプロパティ走査)
const sampleObject = {
name: "Tanaka",
age: 23,
hobbies: ["music", "movies", "sports"],
address: {
street: "50 main st",
city:"Osaka",
state:"Osaka",
},
};
for (const property in sampleObject) {
console.log(`${property}: ${sampleObject[property]}`);
}
forof(配列走査)
const sampleTasks = [
{
id: 1,
text: "Take out trash",
isCompleted: true,
},
{
id: 2,
text: "Meeting with boss",
isCompleted: true,
},
{
id: 3,
text: "Dentist appt",
isCompleted: false,
},
];
for (const task of sampleTasks) {
console.log(task);
}
whileループ
let count = 0;
while (count < 10) {
console.log(`while loop count: ${count++}`);
}
do-whileループ
let counter = 0;
do {
console.log(`do-while loop count: ${counter}`);
} while (counter++ < 10);
関数定義と呼び出し
関数呼び出し
function sampleFunction() {
console.log('test function');
}
sampleFunction(); //関数呼び出し
引数渡し
単一引数
function singleParam(item) { // 仮引数
console.log(item);
}
singleParam('test item'); // 実引数
複数引数
function multiParams(x, y, z) {
console.log(x + y);
}
multiParams(1, 2, 3, 4); // 正常 3 実引数 > 仮引数
multiParams(1, 2, 3); // 正常 3 実引数 === 仮引数
multiParams(1, 2); // 正常 3 実引数 < 仮引数、ただしzは関数内で未使用
// multiParams(1); // エラー 実引数 < 仮引数、使用される仮引数に渡されない
argumentsオブジェクト
function argumentsExample() {
console.log(arguments);
console.log(arguments[1]);
console.log(arguments.length);
}
argumentsExample(1, 2, 3);
戻り値
function addNumbers(x, y) {
return x + y;
}
console.log(addNumbers(3, 2));
アロー関数
let arrowAdd = (x, y, z) => {
return x + y + z;
}
console.log(arrowAdd(1, 2, 3));
// 単一引数のアロー関数は括弧省略可能
let arrowIncrement = num => {
return num + 10;
}
console.log(arrowIncrement(1));
配列イテレータ
forEach
// forEach イテレータ関数形式
sampleTasks.forEach(function(task) {
console.log(task);
});
console.log("---------------------------------------------------");
// forEach イテレータアロー形式
sampleTasks.forEach(task => {
console.log(task);
});
map
// mapイテレータ
let taskDescriptions = sampleTasks.map(function(task) {
return task.text;
}); // mapの戻り値を受け取る配列taskDescriptionsを定義
console.log(taskDescriptions);
console.log("---------------------------------------------------");
// mapイテレータの結果はインデックスで直接使用可能、特定オブジェクトの特定プロパティ値を取得
let taskDescriptionByIndex = sampleTasks.map(function(task) {
return task.text;
}); // mapの戻り値を受け取る配列taskDescriptionByIndexを定義
console.log(taskDescriptionByIndex[1]);
filter
let filteredTasks = sampleTasks.filter(function(task) {
return task.isCompleted === true; // フィルタ条件に基づいて返却
});
console.log(filteredTasks);
filterとmapの組み合わせ
let filteredTaskDescriptions = sampleTasks.filter(task => {
return task.isCompleted === true;
}).map(task => {
return task.text;
});
console.log(filteredTaskDescriptions);