今回はJavaScriptの組み込み関数について学習しました。
組み込み関数とは?
JavaScriptにあらかじめ定義されている関数
有名なのだと、console.log()
とか、alert()
とかですね。
流石にこの辺は知っていますが、Web制作だとあまり多くの組み込み関数を使用する機会がないので、しっかりキャッチアップしていきます。
文字列を数字に変換
const str = "123";
console.log(str); // "123" (文字型)
const str = "123";
console.log(parseInt(str)); // 123 (数値型)
const str = "123.45";
console.log(parseFloat(str)); // 123.45 (数値型)
console.log(parseInt(str)); // 123 (数値型)
const str = "123abc";
console.log(parseInt(str)); // 123 (数値型)
数字を文字列に変換
const count = 10;
console.log(count.toString()); // "10" (文字型)
文字列の操作
trim()
前後のスペースを除く
※住所の入力などで、ユーザーが不要なスペースを入力した場合にの対策などに使用
const message = " Hello World ";
console.log(message.trim()); // "Hello World"
toUpperCase
大文字に変える
const message = " Hello World ";
console.log(message.toUpperCase()); // "HELLO WORLD"
includes
含まれるかを判定する
※大文字小文字も一致判定してくれる。
console.log(message.includes("Hello")); // true
console.log(message.includes("World")); // true
console.log(message.includes("world")); // false
console.log(message.includes("Yes")); // false
split
引数の値で、区切りを判定
const message = " Hello World ";
console.log(message.split(" "));
// (4) ['', 'Hello', 'World', '']
const message = "080-1234-5678";
console.log(message.split("-"));
// (3) ['080', '1234', '5678']
Mathオブジェクトの関数
Math.round()
四捨五入
console.log(Math.round(5.753)); // 6
Math.max()
引数の中から一番大きい値を出力
console.log(Math.max(1, 3, 99)); // 99
Math.random()
console.log(Math.random()); // 0から1でランダムな数値
Dateオブジェクトの操作
日付の操作
let today = new Date();
console.log(today.toDateString()); // Mon Dec 23 2024
let today = new Date();
console.log(today.getFullYear()); // 2024
繰り返し処理
const numbers = [1, 2, 3, 4];
numbers.forEach((number, index) => {
console.log(index, number);
});
データを加工して新しい関数を作る組み込み関数
map()
配列の各要素に対して指定したコールバック関数を実行し、その結果を新しい配列として返す配列メソッド。元の配列は変更されない
よく使うので重要
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((x) => x * 2);
console.log(doubled); // [2, 4, 6, 8]
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((x) => x * 2);
console.log(doubled); // [2, 4, 6, 8]
// アロー関数を使わない場合
const doubled = numbers.map(function (x) {
return x * 2;
});
filter()
配列の各要素に対して指定した条件を満たす要素だけを抽出し、新しい配列として返す配列メソッド。元の配列は変更されません。
const numbers = [1, 2, 3, 4];
const evens = numbers.filter((x) => x % 2 === 0);
console.log(evens); // [2, 4]
フィルターの応用
前回作った絞り込みの関数

/**
* 配列の名前に指定した文字が含まれるか検索フィルタする関数
*
* @param {string} names 検索対象の名前の配列
* @param {string} substring 検索ワード
*/
function filterNamesBySubstrings(names, substring) {
const filteredNames = [];
for (let i = 0; i < names.length; i++) {
if (names[i].includes(substring)) {
filteredNames.push(names[i]);
}
}
return filteredNames;
}
const names = ["John", "Paul", "George", "Ringo"];
const substring = "o";
const result = filterNamesBySubstrings(names, substring);
console.log(result); // ["John", "George", "Ringo"]
これを組み込み関数のfilter()で書き換えると以下になる。
/**
* 配列の名前に指定した文字が含まれるか検索フィルタする関数
*
* @param {string} names 検索対象の名前の配列
* @param {string} substring 検索ワード
*/
const names = ["John", "Paul", "George", "Ringo"];
const substring = "o";
const result = names.filter((name) => name.includes(substring));
console.log(result); // ["John", "George", "Ringo"]
オブジェクトの操作の組み込み関数
全てのキーだけ配列として取得
let user = {
name: "Yamada",
age: 20,
isAdmin: true,
};
console.log(Object.keys(user)); // ["name", "age", "isAdmin"]
全ての値だけ配列として取得
let user = {
name: "Yamada",
age: 20,
isAdmin: true,
};
console.log(Object.values(user)); // ["Yamada", 20, true]
【二次元配列】キーと値のペアを配列にして出力
let user = {
name: "Yamada",
age: 20,
isAdmin: true,
};
console.log(Object.entries(user)); // [ [ 'name', 'Yamada' ], [ 'age', 20 ], [ 'isAdmin', true ] ]
【二次元配列】応用
const employees = {
Yamada: { department: "Engineering", salary: 1000 },
Suzuki: { department: "Sales", salary: 1200 },
Tanaka: { department: "Engineering ", salary: 800 },
Takada: { department: "Sales", salary: 2000 },
};
const heightEaringEmployees = Object.entries(employees)
.filter(([name, details]) => details.salary > 1000)
.map(([name, details]) => ({ name: name, salary: details.salary }));
console.log(heightEaringEmployees);
// 0:
// name: "Suzuki"
// salary: 1200
// [[Prototype]]: Object
// 1:
// name: "Takada"
// salary: 2000
// [[Prototype]]: Object
感想
多くの組み込み関数を覚えました!
Web制作だと、ここまで組み込み関数を扱う場面が少ないので勉強になりました。
数こなして慣れるしかないかなーと思うので、ブログにも書き写して、頭の片隅から引き出せるように定期的に確認します。
正確な暗記は不要で、引き出せる力だけあれば十分ですからね!