js API

138 阅读1分钟

for in & for of

for in用于遍历对象,获取属性中有哪些值 for of用于遍历可迭代的内容并获取值

reduce

reduce() 方法是 JavaScript 数组对象中的一个高阶函数,用于对数组中的每个元素执行一个指定的回调函数,并将回调函数的返回值累加到一个累加器中,最终返回累加器的值。

Array.prototype.myReduce = function (callback, initialValue) {
    // 判断数组是否为空
    if (this.length === 0) {
        throw new TypeError('Reduce of empty array with no initial value');
    }

    // 判断是否传入初始值
    let accumulator = initialValue !== undefined ? initialValue : this[0];

    // 遍历数组并执行回调函数
    for (let i = initialValue !== undefined ? 0 : 1; i < this.length; i++) {
        accumulator = callback(accumulator, this[i], i, this);
    }

    // 返回累加器的值
    return accumulator;
};
const arr = [1, 2, 3, 4, 5]; 
const product = arr.reduce((accumulator, currentValue) => accumulator * currentValue, 1); 
console.log(product); // 120
const arr = [1, 2, 3, 2, 1, 4, 5, 4];
const uniqueArr = arr.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueArr);

Object.assign

对对象的浅拷贝

深拷贝实现:juejin.cn/post/725291…

判断变量的类型:

blog.csdn.net/u010998803/…

为什么typeof 运算符对于引用类型(如对象、数组等)返回的都是 "object"

typeof 运算符对于引用类型(如对象、数组等)返回的都是 "object",是因为 JavaScript 中的引用类型在内部都被表示为对象。 在 JavaScript 中,引用类型是由对象构成的,而对象是由一组键值对组成的集合。无论是普通对象、数组、函数还是其他引用类型,它们在内部都被表示为对象。