js常用方法大全

81 阅读2分钟

1. 基础对象方法

  • Object.keys(obj) 返回一个由对象的自身可枚举属性名组成的数组。

  • Object.values(obj) 返回一个由对象的自身可枚举属性值组成的数组。

  • Object.entries(obj) 返回一个由对象的自身可枚举属性的 [key, value] 对组成的数组。

    console.log(Object.entries({ a: 1, b: 2 })); // [["a", 1], ["b", 2]]
    

Object.assign(target, ...sources) 将所有可枚举的属性从一个或多个源对象复制到目标对象。

```
const target = { a: 1 };
const source = { b: 2 };
Object.assign(target, source); //  target { a: 1, b: 2 }
```

2. 数组方法

  • Array.prototype.push(...elements) 用途: 向数组的末尾添加一个或多个元素,并返回新数组的长度,改变原数组。
  • Array.prototype.pop() 从数组中删除最后一个元素,并返回被删除的元素,改变原数组。
  • Array.prototype.shift() - 从数组中删除第一个元素,并返回被删除的元素,改变原数组。
  • Array.prototype.unshift(...elements) 向数组的开头添加一个或多个元素,并返回新数组的长度。
  • Array.prototype.map(callback) 创建一个新数组,其中的元素是调用提供的函数处理过的结果。
  • Array.prototype.filter(callback) 创建一个新数组,其中包含所有符合条件的元素。
  • [Array.prototype.reduce(callback, [initialValue])] 将数组中的所有元素通过提供的函数处理,最终计算出一个值, 详情
    const arr = [1, 2, 3];
    const sum = arr.reduce((acc, current) => acc + current, 0);
    console.log(sum); // 6
    

3. 字符串方法

  • String.prototype.toUpperCase() 将字符串转换为大写字母。

  • String.prototype.toLowerCase() 将字符串转换为小写字母。

  • String.prototype.includes(searchString, [position]) 判断字符串是否包含指定的子字符串。

  • String.prototype.indexOf(searchString, [position]) 返回第一次出现指定子字符串的位置,如果未找到,则返回 -1。

  • String.prototype.slice(beginIndex, [endIndex]) 返回一个从 beginIndex 到 endIndex 的子字符串,不包括 endIndex

4. 函数方法

  • Function.prototype.call(thisArg, ...args)

    • 用途: 调用一个函数,并指定 this 的值和参数。

      javascriptCopy Code
      function greet(greeting, name) {
        console.log(`${greeting}, ${name}`);
      }
      greet.call(null, 'Hello', 'World'); // 'Hello, World'
      
  • Function.prototype.apply(thisArg, [argsArray])

    • 用途: 调用一个函数,并指定 this 的值和参数数组。

      javascriptCopy Code
      function sum(a, b) {
        return a + b;
      }
      console.log(sum.apply(null, [1, 2])); // 3
      
  • Function.prototype.bind(thisArg, ...args)

    • 用途: 创建一个新的函数,该函数的 this 被绑定到 thisArg,并且在调用时会传入指定的参数。

      javascriptCopy Code
      function greet(greeting, name) {
        console.log(`${greeting}, ${name}`);
      }
      const greetHello = greet.bind(null, 'Hello');
      greetHello('World'); // 'Hello, World'