1、实现flat,数组拉平

  1. function flatCopy(arr) {
  2. if (!Array.isArray(arr)) return;
  3. const stack = [...arr];
  4. const res = [];
  5. while (stack.length) {
  6. let value = stack.shift();
  7. Array.isArray(value) ? stack.push(...value) : res.push(value);
  8. }
  9. return res;
  10. }
  11. var arr = [1, [2, [3, 4, [5, 6]]]];
  12. console.log("flatCopy", flatCopy(arr)); // [ 1, 2, 3, 4, 5, 6 ]

关于多维数组的解构[…]
image.png

注意:

任意多维数组拉平为一维数组,可以使用暴力:arr.flat(Infinity)
image.png

2、实现map

map()方法根据回调函数映射一个新数组

其中关于回调fn,可以参考这语法:

  1. var new_array = arr.map(function callback(currentValue[, index[, array]]) {
  2. // Return element for new_array
  3. }[, thisArg])

具体实现:

  1. Array.prototype.mapcopy = function (fn) {
  2. const result = [];
  3. for (let i = 0; i < this.length; i++) {
  4. if (!this.hasOwnProperty(i)) continue;
  5. result.push(fn(this[i], i, this));
  6. }
  7. return result;
  8. };
  9. var arr = [1, 2, 4, 3, 5];
  10. const newMap = arr.mapcopy((item) => item + 1);
  11. console.log("newMap", newMap); // [ 2, 3, 5, 4, 6 ]
  12. console.log(arr, "arr"); // [ 1, 2, 4, 3, 5 ]
  • 在原型上添加一个方法
  • 传一个函数和this
  • call 方法传的参数和封装好的map方法的参数是一样的
    1. Array.prototype.fakeMap = function (fn, context) {
    2. let arr = this;
    3. let temp = [];
    4. for (let i = 0; i < arr.length; i++) {
    5. let result = fn.call(context, arr[i], i, arr);
    6. temp.push(result);
    7. }
    8. return temp;
    9. };

3、实现filter

filter()方法返回一个数组,返回的每一项是在回调函数中执行结果true。

  1. Array.prototype.filterX = function (fn) {
  2. const result = []
  3. for (let i = 0; i < this.length; i++) {
  4. if (!this.hasOwnProperty(i)) continue
  5. fn(this[i],i,this) && result.push(this[i])
  6. }
  7. return result
  8. }
  9. let arr = [1,2,3,4,5]
  10. console.log(arr.filterX(item=>item>2)) // [ 3, 4, 5 ]

4、 map VS filter

filter是映射出条件为true的item,map是映射每一个item

5、reduce实现

  1. // reduce语法:
  2. arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
  1. Array.prototype.reduceCopy = function (fn, initValue) {
  2. let result = initValue ? initValue : this[0];
  3. for (let i = initValue ? 1 : 0; i < this.length; i++) {
  4. if (!this.hasOwnProperty(i)) continue;
  5. result = fn(result, this[i], i, this);
  6. }
  7. return result;
  8. };
  9. const arr = [1, 2, 3, 4, 5];
  10. const newArr = arr.reduceCopy((a, b) =>
  11. a * b, 2
  12. )
  13. console.log('newArr', newArr);

6、find 实现

find() 方法返回数组中满足提供的测试函数的第一个元素的值,否则返回 undefined

  1. Array.prototype.findCopy = function (fn) {
  2. let result;
  3. for (let i = 0; i < this.length; i++) {
  4. if (!this.hasOwnProperty(i)) continue;
  5. if (fn(this[i], i, this)) {
  6. result = this[i];
  7. break;
  8. }
  9. }
  10. return result;
  11. };
  12. const arr = [1, 2, 3, 4, 5];
  13. console.log(
  14. "findCopy",
  15. arr.findCopy((item) => item > 6) // undefined
  16. );