js基础

基本数据类型

1.number 浮点数,采用IEEE754标准存储,存在精度问题

// 非整数`a` 和 `b`判断相等使用
const isEqual = a - b <= Number.EPSILON;
// 整数`a` 和 `b` 判断相逢使用
const isEqual = a === b;

2.string 字符串类型

  • 可以使用"或者'括起来
const str1 = 'str1';
console.log('str1');
// 输出 str1
  • 使用`

3.object 对象类型,包括NaN也是object,但这是一个bug

4.symbol es6新增,用于表示一个全局唯一量

可以理解为这样的一个类,只是这个类比较特殊,可以当作object的key使用

class Symbol {
  private #sym: string;
  constructor(sym: string) {
    this.#sym = sym;
  }
  toString() {
    return `Symbol(${this.#sym})`;
  }
}

Reflect.oenKeysObject.keys中的表现不同

前者能获取到symbol类型的key,后者不行

const symbolThree = Symbol('three');
const example = {
  one: 1,
  two: 2,
  [symbolThree]: 3,
  four: 4
};
console.log(Reflect.ownKeys(example));
// 输出 ['one', 'two', 'four', Symbol(three)]
console.log(Object.keys(example));
// 输出 ['one', 'two', 'four'];

5.bigint

可以存储大整数,定义的时候需要在最后加n

const bigIntOne = 9007199254740991n;
const bigIntTwo = 9007199254740992n;
console.log(bigIntOne + bigIntTwo);
// 输出 1801439850943000n

6.undefined

即未定义的,可以手动赋值,也可以不赋值

let a;
console.log(a);
// 输出 undefined

const b = (c, d) => {
  console.log(c);
  console.log(d);
};

b(1);
// 由于dd 没有定义,所以输出 undefined
// 输出 1 undefined

7.function

函数类型,包括箭头函数,匿名function,具名function,class

  • 箭头函数
// 箭头函数
const a = () => {
  console.log('hello world');
};
typeof a;
// 输出 function

// 箭头函数字面量
typeof (() => {
  console.log('hello world');
});
// 输出 function
  • 匿名函数
// 匿名函数
const b = function () {
  console.log('hello world');
};

typeof b;
// 输出 function

// 匿名函数字面量
typeof function () {};
// 输出 function
  • 具名函数
// 具名函数
function c() {
  console.log('hello world');
}

typeof c;
// 输出 function

// 具名函数字面量
typeof function c() {};
// 输出 function
  • 具名类
// 具名类
class D {
  constructor() {
    console.log('hello world');
  }
}

typeof D;
// 输出 function

typeof class A {};
// 输出 function
  • 匿名类
// 匿名类
const D = class {
  constructor() {
    console.log('hello world');
  }
};
typeof D;
// 输出 function

// 字面量类
typeof class {
  constructor() {
    console.log('hello world');
  }
};
// 输出 function

8.boolean

true or false

可以通过typeof来获得一个变量的基本数据类型