jsの基本的なデータ型:Number、String、Number、Null、Undefined、これらを知っていれば大丈夫です〜
データ型を文字列に変換
変換方法 1: toString() メソッドを使用する
変換方法 2: String() 関数を使用する
let a = 123;
console.log(a.toString()) // '123'
let b = true
console.log(b.toString()) // 'true'
let c = null;
console.log(c.toString()) // 报错
let d = undefined
console.log(d.toString()) // 报错
let e = 123;
console.log(String(d)) // '123'
let f = true
console.log(String(f)) // 'true'
// null和undefined调用toString()或String()时不一样的
let g = null;
console.log(String(e)) // 'null'
let h = undefined
console.log(String(f)) // 'undefined'
要約:
1. toString() および String() を呼び出すと、元のデータ型を変更せずに文字列型のデータが返されます
2.toString() は null および undefined を文字列に変換できません. null および nudefined を文字列に変換する必要がある場合は, String () を使用できます.
データ型を Number 型に変換する
変換方法 1: Number() メソッドを使用する
変換式2:parseInt()メソッド/parseFloat()メソッドを使用
let a = '123'
console.log(Number(a)) // 123
// 空字符串
let b = ''
console.log(Number(b)) // 0
let c = true
console.log(Number(c)) // 1
let d = false
console.log(Number(b)) // 0
let e = null;
console.log(Number(e)) // 0
let g = undefined
console.log(Number(g)) // NaN
// 如果纯数字和Number方法作用时一样的
let h = '123'
console.log(parseInt(h))
// 如果不是纯数字则只取整数数字
let i = '123.12px'
console.log(parseInt(h)) // 123
// parseFloat() 小数也会保留
let j = '1321.144px'
console.log(parseFloat(i)) // 1321.144
//如果对非String使用parseInt()获知parseFloat()
// 他会先将其转换成String然后再进行操作
let k = true
console.log(parseInt(k)) // NaN
let l = null
console.log(parseInt(l)) // NaN
let n = undefined
console.log(parseInt(n)) // NaN
要約:
1. 純粋な数値の文字列は Number() 関数を介して直接変換されます
2. 純粋な数値ではなく、数値変換を使用する場合、型は NaN になりますが、データ型は数値型のままです
3.文字列にスペースがある場合、文字がない場合は0に変換されます
4.デジタルのブール値 true は 1、false は 0
5. Null からデジタル Null は 0
6. undefined は NaN
文字列を特別に処理する 2 つの方法
parseInt()
1. 純粋な数値に対する文字列効果は Number() と一致しています
2.非純粋な数字、英語で始まらない場合、整数のみが取得されます
3. 英語で始まる非純粋な数字は NaN です
4.parseInt() を使用して整数を取得できます
pressFloat()
1. 純粋な数値に対する文字列効果は Number() と一致しています
2.非純粋な数字、英語で始まらない場合はすべての数字が採用されます
3. 英語で始まる非純粋な数字は NaN です
データ型をブール値に変換
変換方法: Boolean() を使用
let a = 123
console.log(Boolean(a)) // true
let b = -123
console.log(Boolean(b)) // true
let c = 0
console.log(Boolean(c)) // false
let d = NaN
console.log(Boolean(d)) // false
let e = 'test'
console.log(Boolean(e)) // true
let f = ''
console.log(Boolean(f)) // false
let g = null
console.log(Boolean(g)) // false
let h = undefined
console.log(Boolean(h)) // fasle
// 对象也为true
let i = {
name: '法外狂徒',
age: 22
}
console.log(Boolean(i)) // true
要約:
1. 数値型からブール型へ: 0 と NaN 以外は true
2. 文字列型からブール型へ: 空の文字列を除いて、残りは真です
3. null と undefined の両方が false に変換されます
4. オブジェクトも true に変換されます
結論:
js にはいくつかのデータ型しかありませんが、型を処理するのはまだ頭の中で少し面倒です. データ型の変換に慣れていると、コードを書くときにいくつかの小さな問題を回避することができます.通常はバグを書きますもっと注意してください、それでも問題ありません、友達、さあ、あなたの仕事がうまくいくことを願っています〜
以上、あくまで個人的な感想です 間違い等ありましたらご指摘よろしくお願いします~