文字列
文字列について ▲
Javascript で文字列を扱う方法は以下の三種類である
- ''(シングルクォート)
- ""(ダブルクォート)
- ``(バッククォート)
シングルクォートとダブルクォートは同じ機能を持つが、バッククォートはテンプレートリテラルという上位互換のような機能をもっているため覚えておくこと
文字列(String型)には様々なメソッドが用意されており、こちらのページから確認することができる
文字列を含む計算 ▲
JavaScript で文字列を含む計算を行った場合について以下に記載する
main.js
// 文字列を含む計算
let a = '10';
let b = 10;
let result = a + b;
console.log(result, typeof result); // 1010 string
result = a - b;
console.log(result, typeof result); // 0 number
result = a * b;
console.log(result, typeof result); // 100 number
result = a / b;
console.log(result, typeof result); // 1 number
result = a % b;
console.log(result, typeof result); // 0 number
result = a ** b;
console.log(result, typeof result); // 10000000000 number
/**
* 結論:
* +演算子による加算は対応可能なため、b を文字列に変換して処理が行われている
* +演算子による加算以外は a が文字列のままだと対応できないため、
* 自動的に a が数値へと変換されている
*/
NaNについて ▲
NaN とは Not a Number の略であり、数値じゃないということを示すNumber型の値である
main.js
// 数値に変換できない文字列
let a = 'Hello';
let b = 10;
let result = a - b;
console.log(result, typeof result); // NaN 'number'
明示的な型変換 ▲
文字列を明示的に別の型へ変換する方法を以下に記載する
main.js
// 文字列を数値に変換する
const userInput = '10.9';
let result;
console.log(Number(userInput) + 10); // 20.9
console.log(parseInt(userInput) + 10); // 20
console.log(parseFloat(userInput) + 10); // 20.9
console.log(+userInput + 10); // 20.9
// 数値を文字列に変換する
const tenNumber = 10;
console.log('10' + String(tenNumber)); // 1010
console.log('10' + tenNumber.toString()); // 1010
目次