js五种基本数据类型:string, number, boolean, null, undefined

/**
 * 五种基本数据类型:string, number, boolean, null, undefined
 */
// undefined
// 声明变量foo,未声明变量bar
var foo;
console.log(`typeof foo: ${foo}`, `typeof bar: ${bar}`); // typeof foo: undefined typeof bar: undefined
if (foo === undefined) { // foo全等于undefined
    console.log('foo全等于undefined');
} else {
    console.log('foo不全等于undefined');
}
if (typeof bar === 'undefined') { // bar全等于undefined
    console.log('bar全等于undefined');
} else {
    console.log('bar不全等于undefined');
}
// typeof 返回字符串类型
console.log(`typeof (typeof foo): ${typeof (typeof foo)}`); // typeof (typeof foo): string
// 定义函数f()但没有函数体,默认为undefined
function f() { }
console.log(`typeof f(): ${typeof f()}`, `f() === undefined: ${f() === undefined}`); // typeof f(): undefined f() === undefined: true

// null
console.log(`typeof Null: ${typeof Null}`); // typeof Null: undefined
console.log(`typeof null: ${typeof null}`); // typeof null: object

// string
// 常用转义字符
// ---------------------------------------------------------------------------
// \n        换行
// \t        制表符
// \b        空格
// \r        回车
// \f        换页符
// \\        反斜杠
// \'        单引号
// \"        双引号
// \0nnn     八进制代码 nnn 表示的字符(n 是 0 到 7 中的一个八进制数字)
// \xnn      十六进制代码 nn 表示的字符(n 是 0 到 F 中的一个十六进制数字)
// \unnnn    十六进制代码 nnnn 表示的 Unicode 字符(n 是 0 到 F 中的一个十六进制数字)
// ---------------------------------------------------------------------------
var foo = 'hello';
console.log(`typeof foo: ${typeof foo}`); // typeof foo: string

// boolean
var right = true,
    wrong = false;
console.log(`typeof right: ${typeof right}, typeof wrong: ${typeof wrong}`); // typeof right: boolean, typeof wrong: boolean

// number
// 整型
var foo = 100;
console.log(`typeof foo: ${typeof foo}`); // typeof foo: number
// 八进制
var foo = 017;
console.log(foo); // 15
// 十六进制
var foo = 0xAB;
console.log(foo) // 171
// 浮点数
var foo = 23.01;
console.log(foo); // 23.01
// 最大值
console.log(`Number.MAX_VALUE = ${Number.MAX_VALUE}`); // Number.MAX_VALUE = 1.7976931348623157e+308
// 最小值
console.log(`Number.MIN_VALUE = ${Number.MIN_VALUE}`); // Number.MIN_VALUE = 5e-324
// 正无穷大
console.log(`Number.POSITIVE_INFINITY = ${Number.POSITIVE_INFINITY}`); // Number.POSITIVE_INFINITY = Infinity
// 负无穷大
console.log(`Number.NEGATIVE_INFINITY = ${Number.NEGATIVE_INFINITY}`); // Number.NEGATIVE_INFINITY = -Infinity
// isFinite 验证是有限数字
var foo = Number.POSITIVE_INFINITY,
    bar = foo * 3;
if (isFinite(bar)) { // bar是无穷大数字
    console.log('bar是有限数字');
} else {
    console.log('bar是无穷大数字');
}
// NaN 不是一个数字,特殊数值,不可用于直接计算
var foo = 'hello';
if (isNaN(foo)) { // foo不是数字
    console.log('foo不是数字');
} else {
    console.log('foo是数字');
}

猜你喜欢

转载自www.cnblogs.com/goujian/p/11703642.html