Javascript Info阅读

Javascript Info阅读

YoungYa 16 2024-08-29
https://zh.javascript.info

现代人学习Javascript必读物

数据类型

7 种原始类型 1 种引用类型

  1. Number

  2. BigInt

  3. String

  4. Boolean

  5. null

  6. undefined

  7. Object

  8. Symbol

这一部分值得提一下的还有就是 typeof 运算符

typeof undefined // "undefined"

typeof 0 // "number"

typeof 10n // "bigint"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object"  (1)

typeof null // "object"  (2)

typeof alert // "function"  (3)

总结一下上面typeof打印出来的结果有什么

  1. number

  2. bigint

  3. string

  4. boolean

  5. undefined

  6. symbol

  7. object

  8. function

都是八个,仔细再看一眼,😲,不对,为什么typeof null 会是object呢?

这是官方承认的 typeof 的错误,这个问题来自于 JavaScript 语言的早期阶段,并为了兼容性而保留了下来。null 绝对不是一个 objectnull 有自己的类型,它是一个特殊值。typeof 的行为在这里是错误的。

。。。中间已经读完了,没有写笔记

时间和日期

JSON方法 toJSON

JSON 支持以下数据类型:

  • Objects { ... }

  • Arrays [ ... ]

  • Primitives:

    • strings,

    • numbers,

    • boolean values true/false

    • null

不知道你是否发现其中没有Symbol unefined 以及 属性方法

JSON 是语言无关的纯数据规范,因此一些特定于 JavaScript 的对象属性会被 JSON.stringify 跳过。

即:

  • 函数属性(方法)。

  • Symbol 类型的键和值。

  • 存储 undefined 的属性。

let user = {
  sayHi() { // 被忽略
    alert("Hello");
  },
  [Symbol("id")]: 123, // 被忽略
  something: undefined // 被忽略
};

alert( JSON.stringify(user) ); // {}(空对象)

使用JSON方法时还要主要一个问题不得有循环引用

举个栗子🌰

const obj = {
  val: 1001,
  next: null
}

const obj2 = {
  val: 0010,
  next: null
}

obj.next = obj2;
obj2.next = obj;

JSON.stringify(obj); // Error: Converting circular structure to JSON
flowchart TD obj --next--> obj2 --next--> obj