LOADING

标准库(API)

2023/9/1

最不重要的就是 api,不记得也没关系,重要的是你知道有这个方法

写在这里,可以查阅


实例方法和静态方法

Number.NaN; //这个叫静态属性
Number.isNaN(); //这个叫静态方法
let a = Number.isNaN(b);

Number.prototype.toFixed(); // 这个叫实例方法
let a = 1;
let b = a.toFixed(2);

常用方法

typeof

返回的类型

string,boolean,number,undefined,bigInt,symbol

object,function

console.log(typeof b);

in

属性名 in 对象 —> 判断 属性名 是否在对象自身及其隐式原型

console.log("abc" in obj);

instanceof

判断 object 的原型链中,是否存在 constructor 的原型

如果 object 不是对象(比如是一个原始值),instanceof会返回false

object instanceof constructor;

let arr = [1,2,3];
arr instanceof Array  //arr是不是数组

arr是实例,arr的原型链上有没有Array的原型

输出

alert("hello");  //跳出一个弹窗输出
document.write("hello");  //在页面中输出
console.log("hello"); //在控制台中输出

Number

let num = new Number(1); //得到一个数字对象
let num = Number(1);  //得到一个数字

静态方法

Number.isFinite()

判断传入值是否是一个有限数,除了 Infinity,NaN,-Infinity 以外都为 true

Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false

Number.isFinite(0); // true
Number.isFinite(2e64); // true

Number.isInteger()

如果给定值是整数,则返回布尔值 true。否则为 false

Number.isInteger(0); // true
Number.isInteger(1); // true

Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger("1"); // false

Number.isNaN()

除非是 NaN 其他为 false

Number.parseFloat()和 Number.parseInt()

**要解析的值,会被****强制转换为字符串(不是字符串会先转化为字符串)**。该参数开头的空白会被忽略。

如果第一个非空白字符不能被转换为数字,则返回 NaN

实例方法

Number.prototype.toFixed()

参数:小数点后的位数。应该是一个介于 0 和 100 之间的值,包括 0 和 100。如果这个参数被省略,则被视为 0。

返回:四舍五入返回一个字符串

(2.34).toFixed(1); // '2.3'

Number.prototype.toPrecision()

参数:数字的位数

返回:字符串

toPrecision 保留位数,toFixed 保留小数位数

Number.prototype.toString()

转化为字符串

方法有重写,可以填写参数,转换 2 进制,8 进制等

let c = 12;
c.toString(2); //'1100'

Number.prototype.valueOf()

一般是数字的包装对象调用,得到一个数字

String

直接调用和构造函数调用

var str = new String("hello"); //得到一个字符串对象
var str = String("hello");  //得到一个字符串

实例方法

[Symbol.iterator]

实现了可迭代协议

迭代每一个字符

String.prototype.concat()

concat() 方法将字符串参数连接到调用的字符串,并返回一个新的字符串。

参数:一个或多个字符串(不是字符串强制转换为字符串)

返回:一个包含所提供的多个字符串文本组合的新字符串。

const hello = "Hello, ";
console.log(hello.concat("Kevin", ". Have a nice day."));
// Hello, Kevin. Have a nice day.
"".concat({}); // "[object Object]"

String.prototype.includes()

是否可以在一个字符串中找到另一个字符串

参数:1.要筛选的字符串

2.在字符串中开始搜索 <font style="color:rgb(27, 27, 27);">searchString</font> 的位置。默认值为 <font style="color:rgb(27, 27, 27);">0</font>

返回: true 或 false

String.prototype.indexOf()

是否可以在一个字符串中找到另一个字符串(从头开始)

参数:1.要筛选的字符串

2.在字符串中开始搜索 <font style="color:rgb(27, 27, 27);">searchString</font> 的位置。默认值为 <font style="color:rgb(27, 27, 27);">0</font>

返回:返回索引位置(未找到返回-1)

String.prototype.lastIndexOf()

是否可以在一个字符串中找到另一个字符串(从尾开始)

参数:1.要筛选的字符串

2.返回指定子字符串在小于或等于 <font style="color:rgb(27, 27, 27);">position</font> 的位置中的最后一次出现的索引,默认为 <font style="color:rgb(27, 27, 27);">+Infinity</font>

返回: 返回索引位置,否则为-1

String.prototype.match() 正则

String.prototype.matchALL() 正则

需要学习

String.prototype.padEnd()

重复填充,直到长度到达指定长度,从尾部向后填充

参数:1.填充后的长度

2.填充值

返回:一个字符串

const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"

String.prototype.padStart()

重复填充,直到长度到达指定长度,从头部填充

String.prototype.repeat()

重复当前字符串

参数:数字(次数)

const mood = 'Happy! ';

console.log(`I feel ${mood.repeat(3)}`);
// Expected output: "I feel Happy! Happy! Happy! "

String.prototype.replace() 正则

其中一个、多个或所有匹配的 pattern 被替换为 replacement

如果是替换字符串,则只会替换一次,如果是正则表达式,则根据正则表达式来计算
参数:1.要替换的字符串或正则表达式(pattern

2.替换成什么内容(replacement

返回:方法返回一个新字符串

const paragraph = "I think Ruth's dog is cuter than your dog!";

console.log(paragraph.replace("Ruth's", 'my'));
// Expected output: "I think my dog is cuter than your dog!"

String.prototype.replaceAll() 正则

与 replace 相比就是替换字符串的时候,是匹配多次

String.prototype.search() 正则

匹配正则表达式

参数:正则表达式

返回:如果匹配成功,则返回正则表达式在字符串中首次匹配的索引;否则,返回 -1

String.prototype.split() 正则

切割字符串,返回一个数组

参数:根据什么分割

String.prototype.startsWith()

当前字符串是否以另外一个给定的子字符串开头

参数:字符串

返回:truefalse

String.prototype.endsWith()

endsWith() 方法用于判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false

参数:1.要筛选的字符串

2.预期找到 searchString 的末尾位置。默认为 str.length

返回: true 或 false

const str = "生存还是毁灭,这是一个问题。";

console.log(str.endsWith("问题。")); // true
console.log(str.endsWith("毁灭")); // false
console.log(str.endsWith("毁灭", 6)); // true

String.prototype.substring()

const str = 'Mozilla';

console.log(str.substring(1, 3));
// Expected output: "oz"

参数:

indexStart

要返回的子字符串中包含的第一个字符的索引。(开始)

indexEnd 可选

要返回的子字符串中排除的第一个字符的索引。(结束)

返回:

一个新字符串

String.prototype.slice()

slice() 方法提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。

参数:

indexStart

要返回的子字符串中包含的第一个字符的索引。

indexEnd 可选

要返回的子字符串中排除的第一个字符的索引。

返回:

一个新字符串

const str1 = "The morning is upon us.";
// str1 的长度是 23。
const str2 = str1.slice(1, 8); // he morn
//从1到8,一共7位
const str3 = str1.slice(4, -2); // morning is upon u
//从4到倒数第二(倒数第二不会被截取)
const str4 = str1.slice(12); // is upon us.
const str5 = str1.slice(30); // ""
两者区别
  • 参数处理
    • substring方法在处理参数时,如果结束位置参数小于开始位置参数,它会自动交换这两个参数的位置。此外,如果参数小于 0,substring会将其视为 0 处理。
    • slice方法在处理参数时,不会因为参数的大小而交换它们的位置。对于负数参数,slice会从字符串的末尾开始计数,而不是将负数视为 0。
  • 负数参数的处理
    • substring中,如果提供的参数中包含负数,这些负数参数会被视为 0。
    • 在 slice 中,负数参数被视为从字符串末尾开始计数的索引,例如 slice(-1)会返回字符串的最后一个字符。

String.prototype.toLocaleLowerCase()

转小写

返回一个新的字符串

String.prototype.toLocaleUpperCase()

转大写

返回一个新的字符串

String.prototype.toLowerCase()

转小写,用法与上面基本一致(不扣细节)

返回一个新的字符串

String.prototype.toUpperCase()

转大写,用法与上面基本一致(不扣细节)

返回一个新的字符串

String.prototype.trim()

去两端空格

String.prototype.trimEnd()

去后空格

String.prototype.trimStart()

去前空格

Boolean

//通过new Boolean()将会得一个对象
new Boolean();

//tovalueOf可以得到一个boolean类型值
//toString可以得到一个字符串类型

//如果要转化为boolean类型,直接调用
// 0、-0、null、false、NaN、undefined,"" 这些值为false,其他为true
let b = Boolean(a);

Symbol

symbol 是一种原始数据类型<font style="color:rgb(27, 27, 27);">Symbol()</font> 函数会返回 symbol 类型的值,该类型具有静态属性和静态方法

  1. 它的静态属性会暴露几个内建的成员对象
  2. 它的静态方法会暴露全局的 symbol 注册,且类似于内建对象类
  3. 不支持<font style="color:rgb(27, 27, 27);">new Symbol()</font>语法

每个从 **<font style="color:rgb(27, 27, 27);">Symbol()</font>** 返回的 symbol 值都是唯一的。一个 symbol 值能作为对象属性的标识符;这是该数据类型仅有的目的

内建的成员对象包括 <font style="color:rgb(27, 27, 27);">Object</font>, <font style="color:rgb(27, 27, 27);">Array</font>, <font style="color:rgb(27, 27, 27);">Function</font>, <font style="color:rgb(27, 27, 27);">Date</font>, <font style="color:rgb(27, 27, 27);">Math</font>, <font style="color:rgb(27, 27, 27);">RegExp</font>

内建的 <font style="color:rgb(27, 27, 27);">Symbol</font> 值指的是 JavaScript 语言中预定义的一些特殊 Symbol 值,它们在语言的规范中是预先定义好的,用于实现语言的内建功能或约定

const symbol1 = Symbol();
const symbol2 = Symbol(42);
const symbol3 = Symbol('foo');

console.log(typeof symbol1);
// Expected output: "symbol"

console.log(symbol2 === 42);
// Expected output: false

console.log(symbol3.toString());
// Expected output: "Symbol(foo)"

console.log(Symbol('foo') === Symbol('foo'));
// Expected output: false

在 JavaScript 中,Symbol() 函数创建的 Symbol 是不会全局注册的,它是一种局部的、不可变的数据类型。这意味着使用 Symbol() 创建的每个 Symbol 实例都是唯一的,即使它们的描述文本(可选参数)相同也是如此。

相比之下,Symbol.for() 函数创建的 Symbol 是全局注册的。这意味着通过 Symbol.for() 创建的 Symbol 会被存储在一个全局 Symbol 注册表中,并且可以通过相同的键名检索到同一个 Symbol。

用 symbol 的时候要加[]

在 JavaScript 中,当你使用 Symbol 类型作为对象的属性名时,需要将 Symbol 包裹在方括号 [] 中,这是因为 Symbol 本身是一种特殊的数据类型,直接使用它作为属性名会导致语法错误或意外的行为。

唯一性和保护性

  • Symbol 是一种唯一且不可改变的数据类型,使用它作为属性名可以确保属性名的唯一性,不会与其他属性名冲突。
  • 将 Symbol 包裹在 [] 中,有助于明确标识这是一个 Symbol 类型的属性名,而不是一个普通的字符串。

语法要求

  • 在 JavaScript 中,对象的属性名可以是字符串或 Symbol 类型。当你希望使用 Symbol 作为属性名时,必须使用方括号包裹它,否则会被解析为字符串。
  • 如果直接使用 obj.mySymbol,实际上会访问到一个名为 'mySymbol' 的普通属性,而不是 Symbol 类型的属性。
// 创建一个 Symbol
const mySymbol = Symbol('description');

// 使用 Symbol 作为对象的属性名需要加 []
const obj = {
    [mySymbol]: 'value'
};

console.log(obj[mySymbol]); // 输出: 'value'

通过加 [ ] 使用 Symbol 类型作为属性名,你可以确保正确地利用 Symbol 的唯一性和特性,在对象中创建符号属性。

静态方法

Symbol.for()

**<font style="color:rgb(27, 27, 27);">Symbol.for(key)</font>** 方法会根据给定的键 <font style="color:rgb(27, 27, 27);">key</font>,来从运行时的 symbol 注册表中找到对应的 symbol,如果找到了,则返回它,否则,新建一个与该键关联的 symbol,并放入全局 symbol 注册表中。

语法

Symbol.for(key);
Symbol.for("foo"); // 创建一个 symbol 并放入 symbol 注册表中,键为 "foo"
Symbol.for("foo"); // 从 symbol 注册表中读取键为"foo"的 symbol

Symbol.for("bar") === Symbol.for("bar"); // true,证明了上面说的
Symbol("bar") === Symbol("bar"); // false,Symbol() 函数每次都会返回新的一个 symbol

Symbol.keyFor()

**<font style="color:rgb(27, 27, 27);">Symbol.keyFor(sym)</font>** 方法用来获取全局 symbol 注册表中与某个 symbol 关联的键。如果全局注册表中查找到该 symbol,则返回该 symbol 的 key 值,返回值为字符串类型。否则返回 undefined

Symbol.keyFor(sym);
// 创建一个全局 Symbol
var globalSym = Symbol.for("foo");
Symbol.keyFor(globalSym); // "foo"

var localSym = Symbol();
Symbol.keyFor(localSym); // undefined,

静态属性

Symbol.iterator(迭代器)

**<font style="color:rgb(27, 27, 27);">Symbol.iterator</font>** 为每一个对象定义了默认的迭代器。该迭代器可以被 for…of 循环使用。

const iterable1 = {};

iterable1[Symbol.iterator] = function* () {
  yield 1;
  yield 2;
  yield 3;
};

console.log([...iterable1]);

内置可迭代的类型

array

string

map

set

Symbol.toPrimitive(类型转换内部调用)

**<font style="color:rgb(27, 27, 27);">Symbol.toPrimitive</font>** 是内置的 symbol 属性,其指定了一种接受首选类型并返回对象原始值的表示的方法。它被所有的强类型转换制算法优先调用。

const object1 = {
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') {
      return 42;
    }
    return null;
  },
};

console.log(+object1);
// Expected output: 42

没有 <font style="color:rgb(27, 27, 27);">Symbol.toPrimitive</font> 属性的对象将通过不同的顺序调用 <font style="color:rgb(27, 27, 27);">valueOf()</font><font style="color:rgb(27, 27, 27);">toString()</font> 方法将其转换为原始值。

<font style="color:rgb(27, 27, 27);">Symbol.toPrimitive</font> 允许完全控制原始转换过程。Date.prototype[Symbol.toPrimitive]<font style="color:rgb(27, 27, 27);">"default"</font> 视为 <font style="color:rgb(27, 27, 27);">"string"</font> 并且调用 <font style="color:rgb(27, 27, 27);">toString()</font> 而不是 <font style="color:rgb(27, 27, 27);">valueOf()</font>Symbol.prototype[Symbol.toPrimitive] 忽略 hint,并总是返回一个 symbol,这意味着即使在字符串上下文中,也不会调用 Symbol.prototype.toString(),并且 <font style="color:rgb(27, 27, 27);">Symbol</font> 对象必须始终通过 String() 显式转换为字符串。

下面不重要

Symbol.isConcatSpreadable(数组使用)

内置的 **<font style="color:rgb(27, 27, 27);">Symbol.isConcatSpreadable</font>** 符号用于配置某对象作为 Array.prototype.concat() 方法的参数时是否展开其数组元素。

const alpha = ['a', 'b', 'c'];
const numeric = [1, 2, 3];
let alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric);
// Expected output: Array ["a", "b", "c", 1, 2, 3]

numeric[Symbol.isConcatSpreadable] = false;
alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric);
// Expected output: Array ["a", "b", "c", Array [1, 2, 3]]

Symbol.asyncIterator

**<font style="color:rgb(27, 27, 27);">Symbol.asyncIterator</font>** 符号指定了一个对象的默认异步迭代器。如果一个对象设置了这个属性,它就是异步可迭代对象,可用于for await…of循环。

<font style="color:rgb(27, 27, 27);">Symbol.asyncIterator</font> 是一个用于访问对象的 <font style="color:rgb(27, 27, 27);">[Symbol.asyncIterator]()</font> 方法的内建符号。一个异步可迭代对象必须要有 <font style="color:rgb(27, 27, 27);">Symbol.asyncIterator</font> 属性。、

特性

不可写(不可重新赋值)

不可枚举

不可配置(不能删除)

const myAsyncIterable = new Object();
myAsyncIterable[Symbol.asyncIterator] = async function* () {
  yield "hello";
  yield "async";
  yield "iteration!";
};

for await (const x of myAsyncIterable) {
  console.log(x);
  // expected output:
  //    "hello"
  //    "async"
  //    "iteration!"
}

Symbol.hasInstance(instanceof 使用)

**<font style="color:rgb(27, 27, 27);">Symbol.hasInstance</font>** 用于判断某对象是否为某构造器的实例。因此你可以用它自定义 instanceof 操作符在某个类上的行为。

class MyArray {
  static [Symbol.hasInstance](instance) {
    return Array.isArray(instance);
  }
}
console.log([] instanceof MyArray); // true


obj instanceof A
//等效于
A[Symbol.hasInstance](obj) // Function.prototype[Symbol.hasInstance]

也可以这样判断

class A{

}
let a = new A();
let b = {};
A[Symbol.hasInstance](a) // true
A[Symbol.hasInstance](b) // false

Symbol.species

**<font style="color:rgb(27, 27, 27);">Symbol.species</font>** 是个函数值属性,其被构造函数用以创建派生对象。

你可能想在扩展数组类 <font style="color:rgb(27, 27, 27);">MyArray</font> 上返回 Array 对象。例如,当使用例如 map() 这样的方法返回默认的构造函数时,你希望这些方法能够返回父级的 Array 对象,以取代 <font style="color:rgb(27, 27, 27);">MyArray</font> 对象。<font style="color:rgb(27, 27, 27);">Symbol.species</font> 允许你这么做

class MyArray extends Array {
  // 覆盖 species 到父级的 Array 构造函数上
  static get [Symbol.species]() {
    return Array;
  }
}
var a = new MyArray(1, 2, 3);
var mapped = a.map((x) => x * x);

console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true

Symbol.toStringTag(Object 内部调用)

**<font style="color:rgb(27, 27, 27);">Symbol.toStringTag</font>** 内置通用(well-known)symbol 是一个字符串值属性,用于创建对象的默认字符串描述。它由 Object.prototype.toString() 方法内部访问。

class ValidatorClass {
  get [Symbol.toStringTag]() {
    return 'Validator';
  }
}

console.log(Object.prototype.toString.call(new ValidatorClass()));
// Expected output: "[object Validator]"

Symbol.unscopables(类似属性描述符)

**<font style="color:rgb(27, 27, 27);">Symbol.unscopables</font>** 指用于指定对象值,其对象自身和继承的从关联对象的 with 环境绑定中排除的属性名称。

const object1 = {
  property1: 42,
};

object1[Symbol.unscopables] = {
  property1: true,
};

with (object1) {
  console.log(property1);
  // Expected output: Error: property1 is not defined
}

字符串的内部调用方法

Symbol.match

Symbol.matchAll

Symbol.replace

Symbol.search

Symbol.split

实例方法

Symbol.prototype.[Symbol.toPrimitive]

<font style="color:rgb(27, 27, 27);">[Symbol.toPrimitive]()</font> 方法可将 Symbol 对象转换为 symbol 值。

返回指定的 Symbol 对象的原始值。

JavaScript 调用 <font style="color:rgb(27, 27, 27);">[Symbol.toPrimitive]()</font> 方法将一个对象转换为原始值表示。你不需要自己调用 <font style="color:rgb(27, 27, 27);">[Symbol.toPrimitive]()</font> 方法;当对象需要被转换为原始值时,JavaScript 会自动地调用该方法。

Symbol.prototype.toString()

**<font style="color:rgb(27, 27, 27);">toString()</font>** 方法返回当前 symbol 对象的字符串表示。

symbol 原始值不能转换为字符串

symbol 原始值不能转换为字符串,所以只能先转换成它的包装对象,再调用 <font style="color:rgb(27, 27, 27);">toString()</font> 方法

Symbol("foo") + "bar";
// TypeError: Can't convert symbol to string
Symbol("foo").toString() + "bar";
// "Symbol(foo)bar",就相当于下面的:
Object(Symbol("foo")).toString() + "bar";
// "Symbol(foo)bar"

Symbol.prototype.valueOf()

Symbol 值的 **<font style="color:rgb(27, 27, 27);">valueOf()</font>** 方法会返回该符号(symbol)的值。

const symbol1 = Symbol('foo');

console.log(typeof Object(symbol1));
// Expected output: "object"

console.log(typeof Object(symbol1).valueOf());
// Expected output: "symbol"

实例属性

Symbol.prototype.description

**<font style="color:rgb(27, 27, 27);">description</font>** 是一个只读属性,它会返回 Symbol 对象的可选描述的字符串。

console.log(Symbol('desc').description);
// Expected output: "desc"

console.log(Symbol.iterator.description);
// Expected output: "Symbol.iterator"

console.log(Symbol.for('foo').description);
// Expected output: "foo"

console.log(`${Symbol('foo').description}bar`);
// Expected output: "foobar"

bigInt

**<font style="color:rgb(27, 27, 27);">BigInt</font>** 是一种内置对象,它提供了一种方法来表示大于 <font style="color:rgb(27, 27, 27);">2^53 - 1</font> 的整数

获取一个 bigInt 类型

1.可以用在一个整数字面量后面加 <font style="color:rgb(27, 27, 27);">n</font> 的方式定义一个 <font style="color:rgb(27, 27, 27);">BigInt</font> ,如:<font style="color:rgb(27, 27, 27);">10n</font>

2.调用函数 <font style="color:rgb(27, 27, 27);">BigInt()</font>并传递一个整数值或字符串值。

直接调用

BigInt(123);

数学(Math)

API 含义 备注
Math.PI 得到圆周率 π
Math.abs() 求某个数绝对值 传入一个数
Math.ceil() 向上取整 传入一个数
Math.floor() 向下取整 传入一个数
Math.max() 求一个数列中的最大值 把数列依次传入
Math.min() 求一个数列中的最小值 把数列依次传入
Math.random() 得到一个 0-1 之间的随机小数 无参;无法取到 1
Math.round() 返回四舍五入的结果 传入一个数

max

无论多少参数,每一项必须是个数字

console.log(Math.max(1, 3, 2));
// Expected output: 3

console.log(Math.max(-1, -3, -2));
// Expected output: -1

const array1 = [1, 3, 2];

console.log(Math.max(...array1));
// Expected output: 3

round

四舍五入返回数字

random

得到一个 0 到 1 之间的随机数

Math.random()
0.5588771849592984

得到一个两个数字之间的随机数

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

得到一个两个数字之间的随机整数

function getRandomInt(min, max) {
  const minCeiled = Math.ceil(min);
  const maxFloored = Math.floor(max);
  return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled); // 不包含最大值,包含最小值
}

日期(Date)

时间基础知识

单位

单位 名称 换算
hour 小时 1 day = 24 hours
minute 分钟 1 hour = 60 minutes
second 1 minute = 60 seconds
millisecond (ms) 毫秒 1 second = 1000 ms
nanosecond (ns) 纳秒 1 ms = 1000 ns

GMT 和 UTC

世界划分为 24 个时区,北京在东 8 区,格林威治在 0 时区。

GMT:Greenwish Mean Time 格林威治世界时。太阳时,精确到毫秒。

UTC:Universal Time Coodinated 世界协调时。以原子时间为计时标准,精确到纳秒。

国际标准中,已全面使用 UTC 时间,而不再使用 GMT 时间

GMT 和 UTC 时间在文本表示格式上是一致的,均为星期缩写, 日期 月份 年份 时间 GMT,例如:

Thu, 27 Aug 2020 08:01:44 GMT

Unix 时间戳

Unix 时间戳(Unix Timestamp)是 Unix 系统最早提出的概念

它将 UTC 时间 1970 年 1 月 1 日凌晨作为起始时间,到指定时间经过的秒数(毫秒数)

时间戳不分时区

日期 API

构造函数:

new Date(); // 得到一个当前日期对象
new Date(value); // 根据时间戳得到一个日期对象
new Date(dateString); // 根据一个标准日期字符串得到一个日期对象
// 根据年、月、日、小时、分钟、秒、毫秒得到一个日期对象
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

const birthday = new Date("1995-12-17T03:24:00"); // 这是符合 ISO-8601 标准的,将可靠地工作
const birthday = new Date(1995, 11, 17); // 月份是以 0 为索引的
const birthday = new Date(1995, 11, 17, 3, 24, 0);
const birthday = new Date(628021800000); // 传递纪元时间戳参数
API 含义 备注
Date.now() 得到当前时间戳 无参
Date.prototype.getFullYear() 得到年 无参;本地时间;
Date.prototype.getMonth() 得到月 无参;本地时间;范围 0-11
Date.prototype.getDate() 得到日 无参;本地时间;
Date.prototype.getHours() 得到小时 无参;本地时间;
Date.prototype.getMinutes() 得到分钟 无参;本地时间;
Date.prototype.getSeconds() 得到秒 无参;本地时间;
Date.prototype.getMilliseconds() 得到毫秒 无参;本地时间;
Date.prototype.toLocaleString() 得到日期本地的表示方式

对象

构造函数

  • 如果该值是 null 或者 undefined,它会生成并返回一个空对象。
  • 如果该值已经是一个对象,则返回该值。
  • 否则,它将返回与给定值对应的类型的对象。例如,传递 BigInt 基本类型会返回一个 BigInt 封装对象。

调用构造函数一定会返回一个对象

//都可以创建一个对象
const o = new Object();
const o = new Object(undefined);
const o = new Object(null);

//可以创建一个Number
const a = new Object(2);

直接调用

效果一致

静态方法

Object.assign()

将一个或者多个源对象中所有可枚举****自有属性复制到目标对象,并返回修改后的目标对象。

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

//source可以有多个,改变原来的target
const returnedTarget = Object.assign(target, source);

Object.create()

以一个现有对象作为原型,创建一个新对象。

是一种继承方式

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten

me.printIntroduction();
// Expected output: "My name is Matthew. Am I human? true"


//会创建一个没有隐式原型的对象
let obj = Object.create(null);


//这就是一个数组,他把数组的原型作为自己的隐式原型
let obj = Object.create(Array.prototype);

Object.defineProperty(obj,property,descriptor)

属性描述符

参数一:obj(绑定属性的目标对象)

参数二:property(绑定的属性名)

参数三:descriptor(属性描述(配置),且此参数本身为一个对象

{
  value: 10, //设置值
  writable: false, // 是否可以重写
  enumerable: false, // 是否可以遍历
  configurable: false, // 不可修改描述符本身,不可在其他地方再进行Object.defineProperty对其属性进行操作
  get: function () {
    return 123;
  }, // 读取器 getter
  set: function (val) {
    throw new Error(
      `兄弟,你正在给a这个属性重新赋值,你所赋的值是${val},但是,这个属性是不能复制,你再考虑考虑`
    );
  }
}
var obj = {
  b: 2,
};

// 得到属性描述符
let desc = Object.getOwnPropertyDescriptor(obj, "a");
console.log(desc);

// 设置属性描述符
Object.defineProperty(obj, "a", {
  value: 10,
  writable: false, // 不可重写
  enumerable: false, // 不可遍历
  configurable: false, // 不可修改描述符本身,不可在其他地方再进行Object.defineProperty对其属性进行操作
  get: function () {
    return 123;
  }, // 读取器 getter
  set: function (val) {
    throw new Error(
      `兄弟,你正在给a这个属性重新赋值,你所赋的值是${val},但是,这个属性是不能复制,你再考虑考虑`
    );
  }, // 设置器 setter
});

当你打开属性面板有三个点隐藏说明他是 get 属性,在你点击三个点的时候进行动态计算

Object.defineProperties()

同时定义多个属性

const obj = {};
Object.defineProperties(obj, {
  property1: {
    value: true,
    writable: true,
  },
  property2: {
    value: "Hello",
    writable: false,
  },
  // 等等……
});

Object.getOwnPropertyDescriptor(obj, propertyName)

返回一个对象描述给定对象上特定属性(即直接存在于对象上而不在对象的原型链中的属性)的配置。返回的对象是可变的,但对其进行更改不会影响原始属性的配置。

const user = {
name: 'monica',
age: 17
}

Object.getOwnPropertyDescriptor(user, 'name');
/_
{
value: 'monica',
configurable: true, // 该属性的描述符是否可以被重新定义
enumerable: true, // 该属性是否允许被遍历,会影响 for-in 循环
writable: true // 该属性是否允许被修改
}
_/

Object.getOwnPropertyDescriptors()

返回给定对象的所有自有属性描述符。

返回的是一个对象,key 为要查询的 key,value 为属性描述符(当前状态)

const object1 = {
  a:42,
  b:24
};

{
  "a": {
    "value": 42,
    "writable": true,
    "enumerable": true,
    "configurable": true
  },
  "b": {
    "value": 24,
    "writable": true,
    "enumerable": true,
    "configurable": true
  }
}

Object.freeze()

Object.freeze() 静态方法可以使一个对象被冻结。冻结对象可以防止扩展,并使现有的属性不可写入和不可配置

被冻结的对象不能再被更改:

  1. 不能添加新的属性
  2. 不能移除现有的属性
  3. 不能更改它们的可枚举性、可配置性、可写性或值
  4. 对象的原型也不能被重新指定。
const obj = {
  prop: 42,
};

Object.freeze(obj);

obj.prop = 33;
// Throws an error in strict mode

console.log(obj.prop);
// Expected output: 42

解冻

let thawedObj = Object.assign({}, obj);
// 或者
let thawedObj = { ...obj };

Object.isFrozen()

判断一个对象是否被冻结

Object.preventExtensions()

可以防止新属性被添加到对象中(即防止该对象被扩展)。它还可以防止对象的原型被重新指定。

const object1 = {};

Object.preventExtensions(object1);

try {
  Object.defineProperty(object1, "property1", {
    value: 42,
  });
} catch (e) {
  console.log(e);
  // Expected output: TypeError: Cannot define property property1, object is not extensible
}

Object.isExtensible()

判断一个对象是否是可扩展的(是否可以在它上面添加新的属性)

Object.seal()

密封一个对象会阻止其扩展并且使得现有属性不可配置。密封对象有一组固定的属性:不能添加新属性、不能删除现有属性或更改其可枚举性和可配置性、不能重新分配其原型。只要现有属性的值是可写的,它们仍然可以更改seal() 返回传入的同一对象

const object1 = {
  property1: 42,
};

Object.seal(object1);
object1.property1 = 33;
console.log(object1.property1);
// Expected output: 33

delete object1.property1; // Cannot delete when sealed
console.log(object1.property1);
// Expected output: 33

Object.isSealed()

判断一个对象是否被密封。

Object.getOwnPropertyNames()

返回一个数组,其包含给定对象中所有自有属性(包括不可枚举属性,但不包括使用 symbol 值作为名称的属性)

const object1 = {
  a: 1,
  b: 2,
  c: 3,
};

console.log(Object.getOwnPropertyNames(object1));
// Expected output: Array ["a", "b", "c"]

Object.getOwnPropertySymbols()

返回一个包含给定对象所有自有 Symbol 属性的数组。

const object1 = {};
const a = Symbol("a");
const b = Symbol.for("b");
const c = 1;

object1[a] = "localSymbol";
object1[b] = "globalSymbol";
object1[c] = "123";

const objectSymbols = Object.getOwnPropertySymbols(object1);

console.log(objectSymbols);
//> Array [Symbol(a), Symbol(b)]
console.log(objectSymbols.length);
// Expected output: 2

Object.hasOwn()

如果指定的对象自身有指定的属性,则返回 true,否则为 false

const object1 = {
  prop: "exists",
};

console.log(Object.hasOwn(object1, "prop"));
// Expected output: true

console.log(Object.hasOwn(object1, "toString"));
// Expected output: false

console.log(Object.hasOwn(object1, "undeclaredPropertyValue"));
// Expected output: false

Object.entries(object)

参数:对象

返回值:一个由给定对象自有的可枚举字符串键属性的键值对组成的数组。(得到的是一个二维数组)

每个键值对都是一个包含两个元素的数组:

第一个元素是属性的键(始终是字符串)

第二个元素是属性值。

const object1 = {
  a: "somestring",
  b: 42,
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

Object.fromEntries()

将键值对列表转换为一个对象(二维数组转对象)

const entries = new Map([
  ["foo", "bar"],
  ["baz", 42],
]);

const obj = Object.fromEntries(entries);

console.log(obj);
// Expected output: Object { foo: "bar", baz: 42 }
const arr = [
  ["0", "a"],
  ["1", "b"],
  ["2", "c"],
];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }

Object.setPrototypeOf()

设置实例的隐式原型

let obj = {};
obj.__proto__ = 123;

//两者相等

Object.setPrototypeOf(obj, 123);

Object.getPrototypeOf()

返回指定对象的原型(即内部 [[Prototype]] 属性的值)

const prototype1 = {};
const object1 = Object.create(prototype1);

console.log(Object.getPrototypeOf(object1) === prototype1);
// Expected output: true

console.log(Object.getPrototypeOf(object1));
{
} //里面有原型链

Object.is()

确定两个值是否为相同值

console.log(Object.is("1", 1));
// Expected output: false

console.log(Object.is(NaN, NaN));
// Expected output: true

console.log(Object.is(-0, 0));
// Expected output: false

const obj = {};
console.log(Object.is(obj, {}));
// Expected output: false

Object.keys()

返回一个由给定对象自身的可枚举的字符串键属性名组成的数组

const object1 = {
  a: "somestring",
  b: 42,
  c: false,
};

console.log(Object.keys(object1));
// Expected output: Array ["a", "b", "c"]

Object.values()

返回一个给定对象的自有可枚举字符串键属性值组成的数组。

const object1 = {
  a: "somestring",
  b: 42,
  c: false,
};

console.log(Object.values(object1));
// Expected output: Array ["somestring", 42, false]

实例方法

Object.prototype.hasOwnProperty()

返回一个布尔值,表示对象自有属性(而不是继承来的属性)中是否具有指定的属性。(包括不可枚举属性)

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty("property1"));
// Expected output: true

console.log(object1.hasOwnProperty("toString"));
// Expected output: false

console.log(object1.hasOwnProperty("hasOwnProperty"));
// Expected output: false

Object.prototype.propertyIsEnumerable()

返回一个布尔值,表示指定的属性是否是对象的可枚举自有属性。

const object1 = {};
const array1 = [];
object1.property1 = 42;
array1[0] = 42;

console.log(object1.propertyIsEnumerable("property1"));
// Expected output: true

console.log(array1.propertyIsEnumerable(0));
// Expected output: true

console.log(array1.propertyIsEnumerable("length"));
// Expected output: false

Object.prototype.isPrototypeOf()

用于检查一个对象是否存在于另一个对象的原型链中。

function Foo() {}
function Bar() {}

Bar.prototype = Object.create(Foo.prototype);

const bar = new Bar();

console.log(Foo.prototype.isPrototypeOf(bar));
// Expected output: true
console.log(Bar.prototype.isPrototypeOf(bar));
// Expected output: true

实例属性

object.prototype.constructor

Object实例的 constructor 数据属性返回一个引用,指向创建该实例对象的构造函数。注意,此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。

这个值可写,可配置,不可枚举

let a = {};
a.constructor; //Object() { [native code] }
let b = [];
b.constructor; //Array() { [native code] }

函数

API 含义 备注
Function.prototype.apply() 执行函数,绑定 this 参数列表以数组的形式传递
Function.prototype.call() 执行函数,绑定 this 参数列表依次传递
Function.prototype.bind(obj, …args) 返回一个函数的拷贝,新函数的 this 被绑定为 obj,起始参数被绑定为 args

这三个方法都是用来改变函数内部的 this 指向

常规条件**this 永远指向最后调用它的那个对象,this 永远指向最后调用它的那个对象,this 永远指向最后调用它的那个对象。**

apply(),call(),bind()可以改变函数的 this 指向

var a = {
  name: "Cherry",

  func1: function () {
    console.log(this.name);
  },

  func2: function () {
    setTimeout(
      function () {
        this.func1();
      }.call(a),
      100
    );
  },
};
a.func2();

apply 和 call 的区别是 call 方法接受的是若干个参数列表,而 apply 接收的是一个包含多个参数的数组。

bind 是创建一个新的函数,我们必须要手动去调用

call 与 apply

function m(a, b) {
  console.log(this, a, b);
}

var arr = {};
// m.call(arr, 1, 2); // 调用m函数,让它里面的this指向arr
//call与apply的不同是参数的传递方式
m.apply(arr, [1, 2]);

数组

可迭代

构造函数

使用

new Array()和 Array 效果是一样的,都会创建一个数组

单参数

传入数字会给定长度

const arrayEmpty = new Array(2);

console.log(arrayEmpty.length); // 2
console.log(arrayEmpty[0]); // undefined;实际上是一个空槽
console.log(0 in arrayEmpty); // false
console.log(1 in arrayEmpty); // false

传入其他会作为数组第一项的值

const arrayOfOne = new Array("2"); // 这里是字符串 "2" 而不是数字 2

console.log(arrayOfOne.length); // 1
console.log(arrayOfOne[0]); // "2"

多参数

每一项作为数组的值

const fruits = new Array("Apple", "Banana");

console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"

静态方法

Array.from()

可迭代类数组对象创建一个新的浅拷贝的数组实例(真正的数组)

函数的参数<font style="color:rgb(27, 27, 27);">arguments</font>就是一个类数组

类数组就是有 length 属性,有 0:’a’,1:’b’这样的编号属性

参数

arrayLike

想要转换成数组的类数组或可迭代对象。

mapFn 可选

调用数组每个元素的函数。如果提供,每个将要添加到数组中的值首先会传递给该函数,然后将 mapFn 的返回值增加到数组中。使用以下参数调用该函数:

element

数组当前正在处理的元素。

index

数组当前正在处理的元素的索引。

thisArg 可选

执行 mapFn 时用作 this 的值。

console.log(Array.from("foo"));
// Expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], (x) => x + x));
// Expected output: Array [2, 4, 6]

Array.isArray()

用于确定传递的值是否是一个数组。(必须要一个真正的数组,类数组不行)

console.log(Array.isArray([1, 3, 5]));
// Expected output: true

console.log(Array.isArray("[]"));
// Expected output: false

console.log(Array.isArray(new Array(5)));
// Expected output: true

console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false

Array.of()

与构造函数创建数组的区别就是单参数传入数字的时候也是给定值,而不是给定数组长度

实例方法

Array.prototype.at()

给一个数组下标,相等于通过 a[1]访问

Array.prototype.concat()

用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

但此方法是浅拷贝,不会深度遍历

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3,10);

console.log(numbers);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9,10]

Array.prototype.every()

every() 方法测试一个数组内的所有元素是否都能通过指定函数的测试。

它返回一个布尔值。

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true

Array.prototype.some()

**<font style="color:rgb(27, 27, 27);">some()</font>** 方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。它不会修改数组。

语法

some(callbackFn)
some(callbackFn, thisArg)
const array = [1, 2, 3, 4, 5];

// Checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// Expected output: true

Array.prototype.filter()

**<font style="color:rgb(27, 27, 27);">filter()</font>** 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。

filter(callbackFn, thisArg)
const words = ["spray", "elite", "exuberant", "destruction", "present"];

const result = words.filter((word) => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

Array.prototype.flat()

创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]

语法

//depth默认为1,可传infinity
flat(depth)

Array.prototype.flatMap()

它等价于在调用 map() 方法后再调用深度为 1 的 flat() 方法(<font style="color:rgb(27, 27, 27);">arr.map(...args).flat()</font>

let arr = [[1, 2], [3, 4], [5, 6]];

let result = arr.flatMap(subArr => subArr.map(num => num * 2));
console.log(result);
// 输出 [2, 4, 6, 8, 10, 12]

Array.prototype.forEach()

遍历数组,没有返回值

只可放在链式调用最后

不能 break 退出

只能使用同步调用(异步操作会在后台执行,forEach 本身不会等待它们完成 )

语法

forEach(callbackFn, thisArg)

Array.prototype.join()

**<font style="color:rgb(27, 27, 27);">join()</font>** 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

语法

join()
join(separator)

Array.prototype.entries()

entries() 方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。

const array1 = ["a", "b", "c"];

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// Expected output: Array [0, "a"]

console.log(iterator1.next().value);
// Expected output: Array [1, "b"]

const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

Array.prototype.keys()

**<font style="color:rgb(27, 27, 27);">keys()</font>** 方法返回一个新的数组迭代器对象,其中包含数组中每个索引的键。

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// Expected output: 0
// Expected output: 1
// Expected output: 2

Array.prototype.values()

**<font style="color:rgb(27, 27, 27);">values()</font>** 方法返回一个新的数组迭代器对象,该对象迭代数组中每个元素的值。

const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value);
}

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

Array.prototype.map()

<font style="color:rgb(27, 27, 27);">map()</font> 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

语法

map(callbackFn, thisArg)

Array.prototype.reduce()

**<font style="color:rgb(27, 27, 27);">reduce()</font>** 方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值

第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被用作初始值,迭代器将从第二个元素开始执行(即从索引为 1 而不是 0 的位置开始)。

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

语法

reduce(callbackFn, initialValue)

callbackFn 参数

1.上一次的计算值

2.当前元素

3.索引

4.整个数组

Array.prototype.reduceRight()

采用从右到左的顺序

Array.prototype.slice()

返回一个新的数组对象,这一对象是一个由 <font style="color:rgb(27, 27, 27);">start</font><font style="color:rgb(27, 27, 27);">end</font> 决定的原数组的浅拷贝(包括 <font style="color:rgb(27, 27, 27);">start</font>,不包括 <font style="color:rgb(27, 27, 27);">end</font>

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

语法

//截取下标arr[start] - arr[end-1]
slice()
slice(start)
slice(start, end)

Array.prototype.toString()

返回一个字符串

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// Expected output: "1,2,a,1a"

以下修改原数组

Array.prototype.copyWithin()

指定位置的元素复制到其他位置(会覆盖原有元素),并返回修改后的数组。

arr.copyWithin(target, start [, end])
  • target:必需。从该位置开始替换数据。如果为负值,则表示从数组末尾开始的偏移量。
  • start:可选。开始复制元素的起始位置。默认为 0 。如果为负值,则表示从数组末尾开始的偏移量。
  • end:可选。停止复制元素的结束位置(不包括该位置的元素)。默认为 arr.length 。如果为负值,则表示从数组末尾开始的偏移量。

例子

let arr = [1, 2, 3, 4, 5];

// 将索引 0 到索引 2 的元素复制到索引 3 开始的位置
arr.copyWithin(3, 0, 3);
console.log(arr);
// 输出 [1, 2, 3, 1, 2]
设置开始位置为索引3,arr[3]
设置开始为索引0,结束位置为索引3(不包括3)
从arr[3]向后一直填充arr[0],arr[1],arr[2]

Array.prototype.fill()

固定值填充一个数组,修改原数组

参数

1.填充值

2.开始位置(可选)

3.结束位置(可选)

const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

Array.prototype.pop() 删末尾

**<font style="color:rgb(27, 27, 27);">pop()</font>** 方法从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"

Array.prototype.push() 进末尾

**<font style="color:rgb(27, 27, 27);">push()</font>** 方法将指定的元素添加到数组的末尾,并返回新的数组长度。

可传多个参数

Array.prototype.shift() 删头

**<font style="color:rgb(27, 27, 27);">shift()</font>** 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

Array.prototype.unshift() 进头

<font style="color:rgb(27, 27, 27);">unshift()</font> 方法将指定元素添加到数组的开头,并返回数组的新长度。

Array.prototype.reverse()

组中的元素顺序将被翻转,变为与之前相反的方向,返回数组的引用

Array.prototype.toRreverse() 不修改原数组

浅拷贝一个原始数组

Array.prototype.sort()

**<font style="color:rgb(27, 27, 27);">sort()</font>** 方法就地对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。

语法

sort()
sort(compareFn)

compareFn有两个参数,可依次比较

Array.prototype.toSort() 不修改原数组

Array.prototype.splice()

就地移除或者替换已存在的元素和/或添加新的元素。

语法

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)

start:默认是 0,表示要改变数组的位置

deleteCount:一个整数,表示数组中要从 <font style="color:rgb(27, 27, 27);">start</font> 开始删除的元素数量。0 表示不删除,不填等于无穷大,从 start 开始全删

剩余参数表示加入数组的值

Array.prototype.toSplice() 不修改原数组

查找相关

Array.prototype.find()

返回数组中满足提供的测试函数的第一个元素的值。否则返回undefined

语法

find(callbackFn, thisArg)

Array.prototype.findIndex()

与 find 的区别就是返回的是索引,没找到返回-1

Array.prototype.findLast()

与 find 的区别是他是从末尾开始查找

Array.prototype.findLastIndex()

与 findIndex 的区别是他是从末尾开始查找

Array.prototype.includes()

用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 <font style="color:rgb(27, 27, 27);">true</font>,否则返回 <font style="color:rgb(27, 27, 27);">false</font>

语法

//fromIndex开始查找位置,默认为0
includes(searchElement, fromIndex)

Array.prototype.indexOf()

返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

语法

indexOf(searchElement, fromIndex)

Array.prototype.lastIndexOf()

与 indexOf 的区别是从后向前查找

查找总结

**<font style="color:rgb(27, 27, 27);">find()</font>** 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

如果需要在数组中找到对应元素的索引,请使用 findIndex()

如果需要查找某个值的索引,请使用 Array.prototype.indexOf()。(它类似于 findIndex(),但只是检查每个元素是否与值相等,而不是使用测试函数。)

如果需要查找数组中是否存在某个值,请使用 Array.prototype.includes()。同样,它检查每个元素是否与值相等,而不是使用测试函数。

如果需要查找是否有元素满足所提供的测试函数,请使用 Array.prototype.some()

关键词含义

thisArg

let mapper = {
  factor: 2,
  map: function (x) {
    return x * this.factor;
  },
};
let arr = Array.from([1, 2, 3], mapper.map, mapper);
console.log(arr); // [2, 4, 6]

callbackFn(element,index,array)

当前遍历元素,索引,整个数组

fromIndex

开始搜索的索引(从零开始),会转换为整数

  • 负索引从数组末尾开始计数——如果 <font style="color:rgb(27, 27, 27);">frommindex < 0</font>,使用 <font style="color:rgb(27, 27, 27);">frommindex + array.length</font>。注意,在这种情况下,仍然从前到后搜索数组。
  • 如果 <font style="color:rgb(27, 27, 27);">fromIndex < -array.length</font> 或者省略了 <font style="color:rgb(27, 27, 27);">fromIndex</font> ,将使用 <font style="color:rgb(27, 27, 27);">0</font>,而导致整个数组被搜索。
  • 如果 <font style="color:rgb(27, 27, 27);">fromIndex >= array.length</font>,数组不会继续搜索并返回 <font style="color:rgb(27, 27, 27);">-1</font>

类型化数组(Uint8Array)

Int8Array: 8 位有符号整数(-128 ~ 127)

Uint8Array: 8 位无符号整数(0 ~ 255)

64 位浮点数:又称为双精度浮点数,它用 1 位表示符号,11 位表示阶码,52 位表示尾数

JS 中的所有数字,均使用双精度浮点数保存

说明在 js 中一个数字占 64 位

//初始化数组
const arr = new Int32Array(10);
//初始化元素并赋值
const arr = Uint8Array.of(12, 5, 6, 7);

//数组长度
console.log(arr.length);

//数组字节数
console.log(arr.byteLength);

注意点

不能增加和删除数据,类型化数组的长度固定

一些返回数组的方法,返回的数组是同类型化的新数组

arrayBuffer

ArrayBuffer:一个对象,用于存储一块固定内存大小的数据。

new ArrayBuffer(字节数);

可以通过属性byteLength得到字节数,可以通过方法slice得到新的 ArrayBuffer

//创建了一个用于存储10个字节的内存空间 const bf = new ArrayBuffer(10);
//可以切割 const bf2 = bf.slice(3, 5); console.log(bf, bf2);

读写 ArrayBuffer

  1. 使用 DataView

通常会在需要混用多种存储格式时使用 DataView

//创建了一个用于存储10个字节的内存空间 const bf = new ArrayBuffer(10);
//创建一个DataView,参数的含义是操作bf这个buffer,从第三位开始,向后操作四位
const view = new DataView(bf, 3, 4); // console.log(view); //设置值
view.setInt16(1, 3); console.log(view); //读值 console.log(view.getInt16(1));
  1. 使用类型化数组

实际上,每一个类型化数组都对应一个 ArrayBuffer,如果没有手动指定 ArrayBuffer,类型化数组创建时,会新建一个 ArrayBuffer

实际上类型化数组里面就有一个字段数组.buffer 表示存储的内存位置

const bf = new ArrayBuffer(10); //10个字节的内存 const arr1 = new Int8Array(bf);
const arr2 = new Int16Array(bf); console.log(arr1 === arr2);
console.log(arr1.buffer === arr2.buffer); arr1[0] = 10; console.log(arr1)
console.log(arr2); const bf = new ArrayBuffer(10); //10个字节的内存 const arr =
new Int16Array(bf); arr[0] = 2344; //操作了两个字节 console.log(arr);

拿到服务器传过来的图片数据信息

async function test(){ const resp = await fetch("./img/liao.jpg") //拿到一个blob
const blob = await resp.blob(); //拿到一个buffer const bf = await
blob.arrayBuffer(); const arr = new Int8Array(bf, 3, 2); console.log(arr) }

fetch 请求图片放到页面中(base64 和 url 生成)

const data = await fetch("http://localhost:3000/public/test.png"); const blob =
await data.blob(); const reader = new FileReader(); reader.onload = function
(event) { // 将图片的 src 属性设置为 base64 编码的数据
document.getElementById('imageDisplay').src = event.target.result; }; //
将二进制数据读取为 base64 编码的字符串 reader.readAsDataURL(blob); const img =
document.createElement('img'); img.src = URL.createObjectURL(blob);
document.body.appendChild(img);