JavaScript笔记

JavaScript 基础知识

数据类型

Number 类型

BigInt 类型

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

null & undefined

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)

数字型转换

变成
undefinedNaN
null0
true 和 false1 and 0

布尔类型转换

变成
0, null, undefined, NaN, ""false
其他值true

对象

垃圾回收

构造函数

约定

Symbol

全局 symbol

// 从全局注册表中读取
let id = Symbol.for("id"); // 如果该 symbol 不存在,则创建它

// 再次读取(可能是在代码中的另一个位置)
let idAgain = Symbol.for("id");

// 相同的 symbol
alert(id === idAgain); // true

对象—原始值转换

hint

为了进行转换,JavaScript 尝试查找并调用三个对象方法:

  1. 调用 obj[Symbol.toPrimitive](hint) —— 带有 symbol 键 Symbol.toPrimitive(系统 symbol)的方法,如果这个方法存在的话,
  2. 否则,如果 hint 是 “string” —— 尝试调用 obj.toString() 或 obj.valueOf(),无论哪个存在。
  3. 否则,如果 hint 是 “number” 或 “default” —— 尝试调用 obj.valueOf() 或 obj.toString(),无论哪个存在。

数据类型

如果想直接调用数字上的一个方法,需要在它的后面放置两个点..。

alert((123456).toString()); // 等于(123456).toString()

字符串

按位(bitwise)NOT技巧

将数字转换为32-bit整数(如果存在小数部分,则删除小数部分),然后对其二进制表示形式中的所有位均取反。

也就是:对于32-bit整数,~n等于-(n+1)

例如:

alert( ~2 ); // -3,和 -(2+1) 相同
alert( ~1 ); // -2,和 -(1+1) 相同
alert( ~0 ); // -1,和 -(0+1) 相同
alert( ~-1 ); // 0,和 -(-1+1) 相同

用在indexOf检查:

let str = "Widget";

if (~str.indexOf("Widget")) {
  alert( 'Found it!' ); // 正常运行
}

数组方法

数组方法备忘单:

sort, reverse, splice 会修改原数组

Map 和 Set

WeakMap 和 WeakSet

Date

函数

new Function

一下三种声明的含义相同:

new Function('a', 'b', 'return a + b'); // 基础语法
new Function('a,b', 'return a + b'); // 逗号分隔
new Function('a , b', 'return a + b'); // 逗号和空格分隔

对象属性配置

属性标志

原型

F.prototype

💯 wiirhan

© 2025 Wiirhan

𝕏 GitHub