(js基础篇)1.数据类型

188 阅读2分钟

说明:js中有8中基本的数据类型(7种原始类型和1种引用类型)

1.Number类型

  • number类型代表整数和浮点数
  • 数字可以进行 '+ - * /'操作
  • 除了常规的数字,还有Infinity -Infinty NaN

Infinity 无穷大
-Infinit 负无穷 NaN代表一个计算错误


代码:

let num = 123; // 定义整数
let floatNum = 123.1; // 定义浮点数
// 打印 加减乘除
console.log( 1 + 2 );  // 3
console.log( 2 - 1 );  // 1
console.log( 2 * 1 );  // 2
console.log( 2 / 1 );  // 2
console.log( 1 / 0 );  // Infinity 正无穷
console.log( '你好' / 3 ); // NaN 代表一个计算错误。

PS:在js中做数学运算是安全的。我们可以做任何事:除以0,将非数字字符串视为数字,等等。脚本永远不会因为一个致命的错误而停止。最坏的情况下,我们会得到NaN的结果。

2.BigInt类型

  • Number类型无法表示大于(2^35-1)或小于-(2^35-1)
  • BigInt类型用于表示任意长度的整数。
  • 可以将n附加到整数字段的末尾来创建BigInt

代码:

// 尾部的 "n" 表示这是一个 BigInt 类型
const bigInt = 1324123412341234123412343123413241342431234n;

3.String类型

  • js中的字符串必须被括在引号里
  • js三种包含字符串的方式:双引号、单引号、反引号

代码:

let name = "John";
let desc = '我很帅';
let content = `${name} say ${desc}`;
console.log(name,desc);  // John 我很帅
console.log(content);   // John say 我很帅

PS:js中没有character类型,只有一种string类型,一个字符串可以包含一个或多个字符。

4.Boolean类型

  • 类型仅包含两个值:truefalse
  • 布尔值也可作为比较的结果

代码
let isTrue = true;
console.log(isTrue); // true
isTrue = false;
console.log(isTrue); // false
let isAdult = 20 > 18;
console.log(isAdult); // true

5."null"值

  • null值不属于上述任何一种类型。

  • 它构成了一个独立的类型,只包含null


    let age = null;

PS:js中的null仅仅是一个代表“无”、“空”或“值未知”的特殊值

6."undefined"值

  • 特殊值undefinednull一样自成类型。
  • undefined的含义是未被赋值
  • 如果一个变量已被声明,但未被赋值,那么它的值就是undefined

代码:

let name;
console.log(name);  // undefined

7.object类型和symbol类型

  • object类型是一个特殊的类型。其他所有的数据类型都被称为“原始类型”
  • object则用于存储数据集合和更复杂的实体
  • symbol类型用于创建对象的唯一标识符

8.typeof运算符

  • typeof运算符返回参数的类型。
  • 支持两种语法形式:1.作为运算符:typeof x 2.函数形式:typeof(x)
  • typeof x的调用会以字符串的形式返回数据类型

代码:

typeof undefined  // "undefined"
typeof 0  // "number"
typeof 10n  // "bigint"
typeof true  // "boolean"
typeof "foo"  // "string"
typeof Symbol("id")  // "symbol"
typeof Math  // "object"
typeof null  // "object"
typeof alert  // "function"