内置方法

数组方法

继承了构造函数Array的属性prototype的方法,继承原型上的方法

数组方法区分

  • 修改原数组:

    • push()最后一位加,返回值都为执行了方法以后数组长度
    • unshift()在第一位前面加,返回值都为执行了方法以后数组长度
    • pop()返回值剪切掉最后一位
    • shift()返回值剪切掉第一位
    • reverse()返回值为翻转数组元素后的数组
    • splice()返回值为修改后的数组,可以删除数组某一项,或多项,可以指定位置增加某一项
    • sort()返回排序以后的数组,按照ASCII码来排序,传入函数参数可以自定义排序条件
  • 新数组上的修改:

    • concat()返回值为整合拼接的新数组
    • toString()返回值为类似数组结构的字符串列表,可以去掉数组的中括号数组元素变为单独的字符串
    • slice()返回修改后的新数组,可以克隆数组,从下标元素(包括)开始截取到最后(参数1),截取的结束下标数组之前(不包括)(参数2),负值时下标元素(包括)开始截取到结束下标元素之前(不包括),还可以将类数组转为数组
    • join()返回值为新的字符串列表,不传参返回跟toString()一样的字符串列表,默认逗号隔开,传参可以指定符号隔开
    • split()返回值为修改后的新数组,不传参可以把字符串转为数组,参数1传入跟分隔字符一样的符号会逗号分隔数组元素,参数1传入空格会分隔所有数组元素包含分隔符号,参数2传入数字会截断下标数组元素之前(不包括)

Array.prototype.push()

将一个或多个元素添加到数组的末尾,并返回该数组的新长度。

  • 返回值

    • 为执行了方法以后数组长度
  • 参数

    • 被添加到数组末尾的元素

参数1/返回值:

  1. var arr = ['a', 'b', 'c'];
  2. //参数1/返回值:
  3. console.log(arr, arr.push('d'));
  4. //["a", "b", "c", "d"] 4
  5. console.log(arr, arr.push(5));
  6. //["a", "b", "c", 5] 4
  7. console.log(arr, arr.push(true));
  8. //["a", "b", "c", true] 4
  9. console.log(arr, arr.push(undefined));
  10. //["a", "b", "c", undefined] 4
  11. console.log(arr, arr.push(null));
  12. //["a", "b", "c", null] 4
  13. console.log(arr, arr.push(NaN));
  14. //["a", "b", "c", NaN] 4
  15. console.log(arr, arr.push(0));
  16. //["a", "b", "c", 0] 4
  17. console.log(arr, arr.push(false));
  18. //["a", "b", "c", false] 4
  19. console.log(arr, arr.push({}));
  20. //["a", "b", "c", {…}] 4
  21. console.log(arr, arr.push([]));
  22. //["a", "b", "c", Array(0)] 4
  23. console.log(arr, arr.push(function () {}));
  24. //["a", "b", "c", ƒ] 4
  25. console.log(arr, arr.push(new String('123')));
  26. //["a", "b", "c", String{"123"}] 4
  27. console.log(arr, arr.push(new Number('123')));
  28. //["a", "b", "c", Number{123}] 4
  29. console.log(arr, arr.push(new Boolean(true)));
  30. //["a", "b", "c", Boolean{true}] 4

参数2/返回值:

  1. //参数2/返回值:
  2. console.log(arr, arr.push('d', 'e'));
  3. //["a", "b", "c", "d", "e"] 5
  4. console.log(arr, arr.push(4, 5));
  5. //["a", "b", "c", 4, 5] 5
  6. console.log(arr, arr.push(true, false));
  7. //["a", "b", "c", true, false] 5
  8. console.log(arr, arr.push(undefined, undefined));
  9. //["a", "b", "c", undefined, undefined] 5
  10. console.log(arr, arr.push(null, null));
  11. //["a", "b", "c", null, null] 5
  12. console.log(arr, arr.push(NaN, NaN));
  13. //["a", "b", "c", NaN, NaN] 5
  14. console.log(arr, arr.push(0, 0));
  15. //["a", "b", "c", 0, 0] 5
  16. console.log(arr, arr.push(false, false));
  17. //["a", "b", "c", false, false] 5
  18. console.log(arr, arr.push({}, {}));
  19. //["a", "b", "c", {…}, {…}] 5
  20. console.log(arr, arr.push([], []));
  21. //["a", "b", "c", Array(0), Array(0)] 5
  22. console.log(arr, arr.push(function () {}, function () {}));
  23. //["a", "b", "c", ƒ, ƒ] 5
  24. console.log(arr, arr.push(new String('123'), new String('456')));
  25. //["a", "b", "c", String{"123"}, String{"456"}] 5
  26. console.log(arr, arr.push(new Number('123'), new Number('456')));
  27. //["a", "b", "c", Number{123}, Number{456}] 5
  28. console.log(arr, arr.push(new Boolean(true), new Boolean(false)));
  29. //["a", "b", "c", Boolean{true}, Boolean{true}] 5

自己写一个push()方法

  • 功能1:数组最后一位添加数组元素
  • 功能2:返回执行方法以后数组长度
  1. /**
  2. * myPush()
  3. * 将一个或多个元素添加到数组的末尾
  4. * @参数 要添加到数组开头的元素或多个元素
  5. * @返回值 执行了方法以后数组长度
  6. */
  7. var arr = [2, 3, 4];
  8. Array.prototype.myPush = function () {
  9. //功能1:传入实参列表
  10. //循环实参列表
  11. for (var i = 0; i < arguments.length; i++) {
  12. // console.log(arguments[i]); //1 2 3
  13. //arr[索引值]数组元素 数组长度正好等于准备添加的标号
  14. //arr[arr.length] -> this[this.length]
  15. this[this.length] = arguments[i];
  16. }
  17. //功能2:返回执行方法以后数组长度
  18. return this.length;
  19. }
  20. console.log(arr.myPush(1, 2, 3)); //6
  21. console.log(arr); //[2, 3, 4, 1, 2, 3]

Array.prototype.unshift()

将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)

  • 返回值

    • 为执行了方法以后数组长度
  • 参数

    • 要添加到数组开头的元素或多个元素
  1. //push
  2. //返回值都为执行了方法以后数组长度
  3. // console.log(Array.prototype);
  4. //push最后一位加
  5. var arr = [2, 3, 4];
  6. arr.push(5); //返回值:4
  7. console.log(arr); //[2, 3, 4, 5]
  8. // arr.push(6, 7); //返回值: 6
  9. console.log(arr); //[2, 3, 4, 5, 6, 7]
  1. //unshift
  2. //在第一位前面加
  3. var arr = [2, 3, 4];
  4. arr.unshift(1); //返回值:4
  5. console.log(arr); //[1, 2, 3, 4]

参数1/返回值:

  1. var arr = ['a', 'b', 'c'];
  2. // //参数1/返回值:
  3. console.log(arr, arr.unshift('d'));
  4. //["d", "a", "b", "c"] 4
  5. console.log(arr, arr.unshift(5));
  6. //[5, "a", "b", "c"] 4
  7. console.log(arr, arr.unshift(true));
  8. //[true, "a", "b", "c"] 4
  9. console.log(arr, arr.unshift(undefined));
  10. //[undefined, "a", "b", "c"] 4
  11. console.log(arr, arr.unshift(null));
  12. //[null, "a", "b", "c"] 4
  13. console.log(arr, arr.unshift(NaN));
  14. //[NaN, "a", "b", "c"] 4
  15. console.log(arr, arr.unshift(0));
  16. //[0, "a", "b", "c"] 4
  17. console.log(arr, arr.unshift(false));
  18. //[false, "a", "b", "c"] 4
  19. console.log(arr, arr.unshift({}));
  20. //[{…}, "a", "b", "c"] 4
  21. console.log(arr, arr.unshift([]));
  22. //[Array(0), "a", "b", "c"] 4
  23. console.log(arr, arr.unshift(function () {}));
  24. //[ƒ, "a", "b", "c"] 4
  25. console.log(arr, arr.unshift(new String('123')));
  26. //[String{"123"}, "a", "b", "c"] 4
  27. console.log(arr, arr.unshift(new Number('123')));
  28. //[Number{123}, "a", "b", "c"] 4
  29. console.log(arr, arr.unshift(new Boolean(true)));
  30. //[Boolean{true}, "a", "b", "c"] 4

参数2/返回值:

  1. //参数2/返回值:
  2. console.log(arr, arr.unshift('d', 'e'));
  3. //["d", "e", "a", "b", "c"] 5
  4. console.log(arr, arr.unshift(4, 5));
  5. //[4, 5, "a", "b", "c"] 5
  6. console.log(arr, arr.unshift(true, false));
  7. //[true, false, "a", "b", "c"] 5
  8. console.log(arr, arr.unshift(undefined, undefined));
  9. //[undefined, undefined, "a", "b", "c"] 5
  10. console.log(arr, arr.unshift(null, null));
  11. //[null, null, "a", "b", "c"] 5
  12. console.log(arr, arr.unshift(NaN, NaN));
  13. //[NaN, NaN, "a", "b", "c"] 5
  14. console.log(arr, arr.unshift(0, 0));
  15. //[0, 0, "a", "b", "c"] 5
  16. console.log(arr, arr.unshift(false, false));
  17. //[false, false, "a", "b", "c"] 5
  18. console.log(arr, arr.unshift({}, {}));
  19. //[{…}, {…}, "a", "b", "c"] 5
  20. console.log(arr, arr.unshift([], []));
  21. //[Array(0), Array(0), "a", "b", "c"] 5
  22. console.log(arr, arr.unshift(function () { }, function () { }));
  23. //[ƒ, ƒ, "a", "b", "c"] 5
  24. console.log(arr, arr.unshift(new String('123'), new String('456')));
  25. //[String, String, "a", "b", "c"] 5
  26. console.log(arr, arr.unshift(new Number('123'), new Number('456'))); //[Number, Number, "a", "b", "c"] 5
  27. console.log(arr, arr.unshift(new Boolean(true), new Boolean(false))); //[Boolean, Boolean, "a", "b", "c"] 5

自己写一个myUnshift()方法

  • 功能1:数组第一位添加数组元素
  • 功能2:返回执行方法以后数组长度
  1. /**
  2. * unshift()
  3. * 将一个或多个元素添加到数组的开头
  4. * @参数 要添加到数组开头的元素或多个元素
  5. * @返回值 执行了方法以后数组长度
  6. */
  7. //用splice()重写原型数组的原型上的unshift()方法myUnshift()
  8. var arr = ['d', 'e', 'f'];
  9. Array.prototype.myUnshift = function () {
  10. for (var i = arguments.length - 1; i >= 0; i--) {
  11. //arr.splice(开始项的下标,剪切长度,剪切以后最后一位开始添加数据)
  12. this.splice(0, 0, arguments[i]);
  13. }
  14. //功能2:返回执行方法以后数组长度
  15. return this.length;
  16. }
  17. console.log(arr.myUnshift('a', 'b', 'c')); //6
  18. console.log(arr); //["a", "b", "c", "d", "e", "f"]

Array.prototype.pop()

从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。

  • 返回值

    • 从数组中删除的元素
    • 当数组为空时返回undefined
  • 参数

    • 没有

数组为空时:

  1. var arr = [];
  2. console.log(arr, arr.pop());
  3. //[] undefined

参数1/返回值:

  1. // //参数1/返回值:
  2. console.log(arr, arr.pop('d'));
  3. //["a", "b"] "c"
  4. console.log(arr, arr.pop(5));
  5. //["a", "b"] "c"
  6. console.log(arr, arr.pop(true));
  7. //["a", "b"] "c"
  8. console.log(arr, arr.pop(undefined));
  9. //["a", "b"] "c"
  10. console.log(arr, arr.pop(null));
  11. //["a", "b"] "c"
  12. console.log(arr, arr.pop(NaN));
  13. //["a", "b"] "c"
  14. console.log(arr, arr.pop(0));
  15. //["a", "b"] "c"
  16. console.log(arr, arr.pop(false));
  17. //["a", "b"] "c"
  18. console.log(arr, arr.pop({}));
  19. //["a", "b"] "c"
  20. console.log(arr, arr.pop([]));
  21. //["a", "b"] "c"
  22. console.log(arr, arr.pop(function () {}));
  23. //["a", "b"] "c"
  24. console.log(arr, arr.pop(new String('123')));
  25. //["a", "b"] "c"
  26. console.log(arr, arr.pop(new Number('123')));
  27. //["a", "b"] "c"
  28. console.log(arr, arr.pop(new Boolean(true)));
  29. //["a", "b"] "c"

参数2/返回值:

  1. // //参数2/返回值:
  2. console.log(arr, arr.pop('d', 'e'));
  3. //["a", "b"] "c"
  4. console.log(arr, arr.pop(4, 5));
  5. //["a", "b"] "c"
  6. console.log(arr, arr.pop(true, false));
  7. //["a", "b"] "c"
  8. console.log(arr, arr.pop(undefined, undefined));
  9. //["a", "b"] "c"
  10. console.log(arr, arr.pop(null, null));
  11. //["a", "b"] "c"
  12. console.log(arr, arr.pop(NaN, NaN));
  13. //["a", "b"] "c"
  14. console.log(arr, arr.pop(0, 0));
  15. //["a", "b"] "c"
  16. console.log(arr, arr.pop(false, false));
  17. //["a", "b"] "c"
  18. console.log(arr, arr.pop({}, {}));
  19. //["a", "b"] "c"
  20. console.log(arr, arr.pop([], []));
  21. //["a", "b"] "c"
  22. console.log(arr, arr.pop(function () {}, function () {}));
  23. //["a", "b"] "c"
  24. console.log(arr, arr.pop(new String('123'), new String('456')));
  25. //["a", "b"] "c"
  26. console.log(arr, arr.pop(new Number('123'), new Number('456')));
  27. //["a", "b"] "c"
  28. console.log(arr, arr.pop(new Boolean(true), new Boolean(false)));
  29. //["a", "b"] "c"

自己写一个myPop()方法

  1. /**
  2. * pop()
  3. * @参数 没有
  4. * @返回值 返回被删的最后一位数组元素
  5. * @数组本身 为空就返回undefined
  6. */
  7. var arr = ['a', 'b', 'c', 'd'];
  8. //写一个myPop()方法
  9. Array.prototype.myPop = function () {
  10. if (this.length === 0) {
  11. return undefined;
  12. }
  13. for (var i = 0; i < this.length; i++) {
  14. var lastElm = this[this.length - 1];
  15. this.splice(-1, 1);
  16. return lastElm;
  17. }
  18. }
  19. console.log(arr.myPop()); //e
  20. console.log(arr); //["a", "b", "c", "d"]

Array.prototype.shift()

从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

  • 返回值

    • 从数组中删除的元素;
    • 如果数组为空则返回undefined 。
  • 参数

    • 没有
  1. //pop()
  2. //pop()没有参数噢
  3. //剪切掉最后一位并返回
  4. var arr = ['a', 'b', 'c'];
  5. console.log(arr.pop()); //c
  6. console.log(arr); //["a", "b"]
  1. //shift()
  2. //shift()没有参数噢
  3. //剪切掉第一位并返回
  4. //可以测试后端传入的未知数据类型
  5. var arr = ['a', 'b', 'c'];
  6. console.log(arr.shift()); //a
  7. console.log(arr); //["b", "c"]

数组为空时:

  1. var arr = [];
  2. console.log(arr, arr.shift());
  3. //[] undefined

参数1/返回值:

  1. // // //参数1/返回值:
  2. console.log(arr, arr.shift('d'));
  3. //["b", "c"] "a"
  4. console.log(arr, arr.shift(5));
  5. //["b", "c"] "a"
  6. console.log(arr, arr.shift(true));
  7. //["b", "c"] "a"
  8. console.log(arr, arr.shift(undefined));
  9. //["b", "c"] "a"
  10. console.log(arr, arr.shift(null));
  11. //["b", "c"] "a"
  12. console.log(arr, arr.shift(NaN));
  13. //["b", "c"] "a"
  14. console.log(arr, arr.shift(0));
  15. //["b", "c"] "a"
  16. console.log(arr, arr.shift(false));
  17. //["b", "c"] "a"
  18. console.log(arr, arr.shift({}));
  19. //["b", "c"] "a"
  20. console.log(arr, arr.shift([]));
  21. //["b", "c"] "a"
  22. console.log(arr, arr.shift(function () {}));
  23. //["b", "c"] "a"
  24. console.log(arr, arr.shift(new String('123')));
  25. //["b", "c"] "a"
  26. console.log(arr, arr.shift(new Number('123')));
  27. //["b", "c"] "a"
  28. console.log(arr, arr.shift(new Boolean(true)));
  29. //["b", "c"] "a"

参数2/返回值:

  1. // // //参数2/返回值:
  2. console.log(arr, arr.shift('d', 'e'));
  3. //["b", "c"] "a"
  4. console.log(arr, arr.shift(4, 5));
  5. //["b", "c"] "a"
  6. console.log(arr, arr.shift(true, false));
  7. //["b", "c"] "a"
  8. console.log(arr, arr.shift(undefined, undefined));
  9. //["b", "c"] "a"
  10. console.log(arr, arr.shift(null, null));
  11. //["b", "c"] "a"
  12. console.log(arr, arr.shift(NaN, NaN));
  13. //["b", "c"] "a"
  14. console.log(arr, arr.shift(0, 0));
  15. //["b", "c"] "a"
  16. console.log(arr, arr.shift(false, false));
  17. //["b", "c"] "a"
  18. console.log(arr, arr.shift({}, {}));
  19. //["b", "c"] "a"
  20. console.log(arr, arr.shift([], []));
  21. //["b", "c"] "a"
  22. console.log(arr, arr.shift(function () {}, function () {}));
  23. //["b", "c"] "a"
  24. console.log(arr, arr.shift(new String('123'), new String('456')));
  25. //["b", "c"] "a"
  26. console.log(arr, arr.shift(new Number('123'), new Number('456')));
  27. //["b", "c"] "a"
  28. console.log(arr, arr.shift(new Boolean(true), new Boolean(false)));
  29. //["b", "c"] "a"

自己写一个myShift()方法

  1. /**
  2. * myShift()
  3. * @参数 没有
  4. * @返回值 返回被删的第一位数组元素
  5. * @数组本身 为空就返回undefined
  6. */
  7. var arr = ['a', 'b', 'c', 'd'];
  8. //myShift()方法
  9. Array.prototype.myShift = function () {
  10. if (this.length === 0) {
  11. return undefined;
  12. }
  13. for (var i = 0; i < this.length; i++) {
  14. var firstElm = this[0];
  15. this.splice(0, 1);
  16. return firstElm;
  17. }
  18. }
  19. console.log(arr.myShift()); //a
  20. console.log(arr); //["b", "c", "d"]

Array.prototype.reverse()

将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。

  • 返回值

    • 颠倒后的原数组。
  • 参数

    • 没有
  1. //reverse()
  2. var arr = [1, 2, 3];
  3. arr.reverse();
  4. console.log(arr); //[3, 2, 1]
  5. var arr2 = ['a', 'b', 'c'];
  6. arr2.reverse();
  7. console.log(arr2); //["c", "b", "a"]

数组为空时:

  1. var arr = [];
  2. console.log(arr, arr.reverse());
  3. //[] []

参数1/返回值:

  1. //参数1/返回值:
  2. console.log(arr, arr.reverse('d'));
  3. //["c", "b", "a"] (3) ["c", "b", "a"]
  4. console.log(arr, arr.reverse(5));
  5. //["c", "b", "a"] (3) ["c", "b", "a"]
  6. console.log(arr, arr.reverse(true));
  7. //["c", "b", "a"] (3) ["c", "b", "a"]
  8. console.log(arr, arr.reverse(undefined));
  9. //["c", "b", "a"] (3) ["c", "b", "a"]
  10. console.log(arr, arr.reverse(null));
  11. //["c", "b", "a"] (3) ["c", "b", "a"]
  12. console.log(arr, arr.reverse(NaN));
  13. //["c", "b", "a"] (3) ["c", "b", "a"]
  14. console.log(arr, arr.reverse(0));
  15. //["c", "b", "a"] (3) ["c", "b", "a"]
  16. console.log(arr, arr.reverse(false));
  17. //["c", "b", "a"] (3) ["c", "b", "a"]
  18. console.log(arr, arr.reverse({}));
  19. //["c", "b", "a"] (3) ["c", "b", "a"]
  20. console.log(arr, arr.reverse([]));
  21. //["c", "b", "a"] (3) ["c", "b", "a"]
  22. console.log(arr, arr.reverse(function () {}));
  23. //["c", "b", "a"] (3) ["c", "b", "a"]
  24. console.log(arr, arr.reverse(new String('123')));
  25. //["c", "b", "a"] (3) ["c", "b", "a"]
  26. console.log(arr, arr.reverse(new Number('123')));
  27. //["c", "b", "a"] (3) ["c", "b", "a"]
  28. console.log(arr, arr.reverse(new Boolean(true)));
  29. //["c", "b", "a"] (3) ["c", "b", "a"]

参数2/返回值:

  1. //参数2/返回值:
  2. console.log(arr, arr.reverse('d', 'e'));
  3. //["c", "b", "a"] (3) ["c", "b", "a"]
  4. console.log(arr, arr.reverse(4, 5));
  5. //["c", "b", "a"] (3) ["c", "b", "a"]
  6. console.log(arr, arr.reverse(true, false));
  7. //["c", "b", "a"] (3) ["c", "b", "a"]
  8. console.log(arr, arr.reverse(undefined, undefined));
  9. //["c", "b", "a"] (3) ["c", "b", "a"]
  10. console.log(arr, arr.reverse(null, null));
  11. //["c", "b", "a"] (3) ["c", "b", "a"]
  12. console.log(arr, arr.reverse(NaN, NaN));
  13. //["c", "b", "a"] (3) ["c", "b", "a"]
  14. console.log(arr, arr.reverse(0, 0));
  15. //["c", "b", "a"] (3) ["c", "b", "a"]
  16. console.log(arr, arr.reverse(false, false));
  17. //["c", "b", "a"] (3) ["c", "b", "a"]
  18. console.log(arr, arr.reverse({}, {}));
  19. //["c", "b", "a"] (3) ["c", "b", "a"]
  20. console.log(arr, arr.reverse([], []));
  21. //["c", "b", "a"] (3) ["c", "b", "a"]
  22. console.log(arr, arr.reverse(function () {}, function () {}));
  23. //["c", "b", "a"] (3) ["c", "b", "a"]
  24. console.log(arr, arr.reverse(new String('123'), new String('456')));
  25. // ["c", "b", "a"] (3) ["c", "b", "a"]
  26. console.log(arr, arr.reverse(new Number('123'), new Number('456')));
  27. //["c", "b", "a"] (3) ["c", "b", "a"]
  28. console.log(arr, arr.reverse(new Boolean(true), new Boolean(false)));
  29. //["c", "b", "a"] (3) ["c", "b", "a"]

写一个myReverse()方法

  1. /**
  2. * myReverse()
  3. * @参数 没有
  4. * @返回值 颠倒后的原数组
  5. */
  6. var arr = ['a', 'b', 'c', 'd'];
  7. var arr2 = [33, 456, 21, 1, 756, 34];
  8. // myReverse()方法
  9. Array.prototype.myReverse = function () {
  10. this.sort(function (a, b) {
  11. return -1;
  12. });
  13. return this;
  14. }
  15. console.log(arr.myReverse()); //["d", "c", "b", "a"]
  16. console.log(arr2.myReverse()); //[34, 756, 1, 21, 456, 33]

Array.prototype.splice()

通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

  • 删除数组某一项
  • 删除数组多项
  • 指定位置增加某一项
  • 返回值

    • 由被删除的元素组成的一个数组。
    • 由被新增元素组成的一个数组。
    • 如果没有删除元素,则返回空数组。
  • 参数

    • start:开始项的下标
    • deleteCount:剪切长度(可选)
    • item:要添加进数组的元素(可选)
  1. //splice
  2. //arr.splice(开始项的下标,剪切长度,剪切以后最后一位开始添加数据)
  3. var arr = ['a', 'b', 'c'];
  4. //arr.splice(下标为1, 剪切1位)
  5. arr.splice(1, 1);
  6. console.log(arr); //["a", "c"]
  7. var arr2 = ['a', 'b', 'c'];
  8. //arr.splice(下标为1, 剪切2位)
  9. arr2.splice(1, 2);
  10. console.log(arr2); //["a"]
  11. var arr3 = ['a', 'b', 'c'];
  12. //arr.splice(下标为1, 剪切2位)
  13. //注意最后一位是没有空格的
  14. arr3.splice(1, 1, 1, 2, 3);
  15. console.log(arr3); //["a", 1, 2, 3, "c"]
  1. var arr = ['a', 'b', 'c', 'e'];
  2. //在c和e中间添加d
  3. //arr.splice(数组长度, 0, 'd');
  4. arr.splice(3, 0, 'd');
  5. console.log(arr); //["a", "b", "c", "d", "e"]
  1. var arr = ['a', 'b', 'c', 'e'];
  2. //在c和e中间添加d
  3. // arr.splice(可以添加负值, 0, 'd')
  4. //-1代表最后一项 -2代表倒数第二项 -3.....
  5. arr.splice(-1, 0, 'd');
  6. console.log(arr); //["a", "b", "c", "d", "e"]

没有参数/返回值:

  1. //原数组保持不变,返回空数组
  2. var arr = ['a', 'b', 'c'];
  3. console.log(arr, arr.splice());
  4. //["a", "b", "c"] []

参数1/返回值:

  • 传入字符串,清空原数组,返回被删的所有数组元素
  • 传入0,清空原数组,返回被删的所有数组元素
  • 如传入数字超过数组长度,原数组不变,返回空数组
  • 如传入数字大于0且小于数组长度,原数组保留第n位和第n+1位的元素跟传入数值n的长度相同,返回除第n位和第n+1位之外被删除的元素
  • 如传为真的数值,相当于转为数值1传值,结果如数值1的结果
  • 如传为假的数值,相当于转为数值0传值,结果如数值0的结果
  • 如传包装类(String, Number)的数值,原数组不变,返回空数组
  • 如传包装类(Boolean)的数值,根据真或假来转换为1/0,得到1/0数值的结果
  1. var arr = ['a', 'b', 'c'];
  2. //参数1/返回值:
  3. console.log(arr, arr.splice('d'));
  4. //[] (3) ["a", "b", "c"]
  5. console.log(arr, arr.splice(-1));
  6. //["a", "b"] ["c"]
  7. console.log(arr, arr.splice(0));
  8. //[] (3) ["a", "b", "c"]
  9. console.log(arr, arr.splice(1));
  10. //["a"] (2) ["b", "c"]
  11. console.log(arr, arr.splice(2));
  12. //["a", "b"] ["c"]
  13. console.log(arr, arr.splice(3));
  14. //["a", "b", "c"] []
  15. console.log(arr, arr.splice(4));
  16. //["a", "b", "c"] []
  17. console.log(arr, arr.splice(true));
  18. //["a"] (2) ["b", "c"]
  19. console.log(arr, arr.splice(undefined));
  20. //[] (3) ["a", "b", "c"]
  21. console.log(arr, arr.splice(null));
  22. //[] (3) ["a", "b", "c"]
  23. console.log(arr, arr.splice(NaN));
  24. //[] (3) ["a", "b", "c"]
  25. console.log(arr, arr.splice(false));
  26. //[] (3) ["a", "b", "c"]
  27. console.log(arr, arr.splice({}));
  28. //[] (3) ["a", "b", "c"]
  29. console.log(arr, arr.splice([]));
  30. //[] (3) ["a", "b", "c"]
  31. console.log(arr, arr.splice(function () {}));
  32. //[] (3) ["a", "b", "c"]
  33. console.log(arr, arr.splice(new String('123')));
  34. //["a", "b", "c"] []
  35. console.log(arr, arr.splice(new Number('123')));
  36. //["a", "b", "c"] []
  37. console.log(arr, arr.splice(new Boolean(true)));
  38. //["a"] (2) ["b", "c"]
  39. console.log(arr, arr.splice(new Boolean(false)));
  40. //[] (3) ["a", "b", "c"]

参数2/返回值:

  • 传入字符串,原数组不变,返回空数组
  • 参数1为元素下标(包括),参数2为删除长度
  • 如删除长度为0,不做删除操作,原数组不变,返回空数组
  • 如删除长度为1,删除1位元素操作,原数组为(数组长度-1)个元素,返回1个被删的下标开始截取的元素
  • 如删除长度为2,删除2位元素操作,原数组为(数组长度-2)个元素,返回2个被删的下标开始截取的元素
  • 如删除长度为n,删除n位元素操作,原数组为(数组长度-n)个元素,返回n个被删的下标开始截取的元素
  • 如传为真的数值,相当于转为数值1传值,结果如数值1的结果
  • 如传为假的数值,相当于转为数值0传值,结果如数值0的结果
  • 如传包装类(String, Number)的数值,原数组不变,返回空数组
  • 如传包装类(Boolean)的数值,根据真或假来转换为1/0,得到1/0数值的结果
  1. var arr = ['a', 'b', 'c'];
  2. //参数2/返回值:
  3. console.log(arr, arr.splice('d', 'e'));
  4. //["a", "b", "c"] []
  5. console.log(arr, arr.splice(-1, -1));
  6. //["a", "b", "c"] []
  7. console.log(arr, arr.splice(-1, 0));
  8. //["a", "b", "c"] []
  9. console.log(arr, arr.splice(-1, 1));
  10. //["a", "b"] ["c"]
  11. console.log(arr, arr.splice(0, 0));
  12. //["a", "b", "c"] []
  13. console.log(arr, arr.splice(0, 1));
  14. //["b", "c"] ["a"]
  15. console.log(arr, arr.splice(0, 2));
  16. //["c"] (2) ["a", "b"]
  17. console.log(arr, arr.splice(0, 3));
  18. //[] (3) ["a", "b", "c"]
  19. console.log(arr, arr.splice(0, 4));
  20. //[] (3) ["a", "b", "c"]
  21. console.log(arr, arr.splice(1, 0));
  22. //["a", "b", "c"] []
  23. console.log(arr, arr.splice(1, 1));
  24. //["a", "c"] ["b"]
  25. console.log(arr, arr.splice(1, 2));
  26. //["a"] (2) ["b", "c"]
  27. console.log(arr, arr.splice(1, 3));
  28. //["a"] (2) ["b", "c"]
  29. console.log(arr, arr.splice(1, 4));
  30. //["a"] (2) ["b", "c"]
  31. console.log(arr, arr.splice(2, 0));
  32. //["a", "b", "c"] []
  33. console.log(arr, arr.splice(2, 1));
  34. //["a", "b"] ["c"]
  35. console.log(arr, arr.splice(2, 2));
  36. //["a", "b"] ["c"]
  37. console.log(arr, arr.splice(2, 3));
  38. //["a", "b"] ["c"]
  39. console.log(arr, arr.splice(2, 4));
  40. //["a", "b"] ["c"]
  41. console.log(arr, arr.splice(3, 0));
  42. //["a", "b", "c"] []
  43. console.log(arr, arr.splice(3, 1));
  44. //["a", "b", "c"] []
  45. console.log(arr, arr.splice(3, 2));
  46. //["a", "b", "c"] []
  47. console.log(arr, arr.splice(3, 3));
  48. //["a", "b", "c"] []
  49. console.log(arr, arr.splice(3, 4));
  50. //["a", "b", "c"] []
  51. console.log(arr, arr.splice(true, false));
  52. //["a", "b", "c"] []
  53. console.log(arr, arr.splice(false, false));
  54. //["a", "b", "c"] []
  55. console.log(arr, arr.splice(false, true));
  56. //["b", "c"] ["a"]
  57. console.log(arr, arr.splice(undefined, undefined));
  58. //["a", "b", "c"] []
  59. console.log(arr, arr.splice(undefined, false));
  60. //["a", "b", "c"] []
  61. console.log(arr, arr.splice(undefined, true));
  62. //["b", "c"] ["a"]
  63. console.log(arr, arr.splice(null, null));
  64. //["a", "b", "c"] []
  65. console.log(arr, arr.splice(NaN, NaN));
  66. //["a", "b", "c"] []
  67. console.log(arr, arr.splice({}, {}));
  68. //["a", "b", "c"] []
  69. console.log(arr, arr.splice([], []));
  70. //["a", "b", "c"] []
  71. console.log(arr, arr.splice(function () {}, function () {}));
  72. //["a", "b", "c"] []
  73. console.log(arr, arr.splice(new String('123'), new String('456')));
  74. //["a", "b", "c"] []
  75. console.log(arr, arr.splice(new Number('123'), new Number('456')));
  76. //["a", "b", "c"] []
  77. console.log(arr, arr.splice(new Boolean(true), new Boolean(false)));
  78. //["a", "b", "c"] []
  79. console.log(arr, arr.splice(new Boolean(true), new Boolean(true)));
  80. //["a", "c"] ["b"]

参数3/返回值:

  • 传入字符串,原数组不变,返回空数组,第0位新增指定元素
  • 根据下标元素(不包括)前加入新增指定元素
  • 如传为真的数值,相当于转为数值1传值,结果如数值1的结果
  • 如传为假的数值,相当于转为数值0传值,结果如数值0的结果
  1. var arr = ['a', 'b', 'c'];
  2. //参数3/返回值:
  3. console.log(arr, arr.splice('d', 'e', 'f'));
  4. //["f", "a", "b", "c"] []
  5. console.log(arr, arr.splice(-1, -1, 'f'));
  6. //["a", "b", "f", "c"] []
  7. console.log(arr, arr.splice(-1, 0, 'f'));
  8. //["a", "b", "f", "c"] []
  9. console.log(arr, arr.splice(-1, 1, 'f'));
  10. //["a", "b", "f"] ["c"]
  11. console.log(arr, arr.splice(0, 0, 'f'));
  12. //["f", "a", "b", "c"] []
  13. console.log(arr, arr.splice(0, 1, 'f'));
  14. //["f", "b", "c"] ["a"]
  15. console.log(arr, arr.splice(0, 2, 'f'));
  16. //["f", "c"] (2) ["a", "b"]
  17. console.log(arr, arr.splice(0, 3, 'f'));
  18. //["f"] (3) ["a", "b", "c"]
  19. console.log(arr, arr.splice(0, 4, 'f'));
  20. //["f"] (3) ["a", "b", "c"]
  21. console.log(arr, arr.splice(1, 0, 'f'));
  22. //["a", "f", "b", "c"] []
  23. console.log(arr, arr.splice(1, 1, 'f'));
  24. //["a", "f", "c"] ["b"]
  25. console.log(arr, arr.splice(1, 2, 'f'));
  26. //["a", "f"] (2) ["b", "c"]
  27. console.log(arr, arr.splice(1, 3, 'f'));
  28. //["a", "f"] (2) ["b", "c"]
  29. console.log(arr, arr.splice(1, 4, 'f'));
  30. //["a", "f"] (2) ["b", "c"]
  31. console.log(arr, arr.splice(2, 0, 'f'));
  32. //["a", "b", "f", "c"] []
  33. console.log(arr, arr.splice(2, 1, 'f'));
  34. //["a", "b", "f"] ["c"]
  35. console.log(arr, arr.splice(2, 2, 'f'));
  36. //["a", "b", "f"] ["c"]
  37. console.log(arr, arr.splice(2, 3, 'f'));
  38. //["a", "b", "f"] ["c"]
  39. console.log(arr, arr.splice(2, 4, 'f'));
  40. //["a", "b", "f"] ["c"]
  41. console.log(arr, arr.splice(3, 0, 'f'));
  42. //["a", "b", "c", "f"] []
  43. console.log(arr, arr.splice(3, 1, 'f'));
  44. //["a", "b", "c", "f"] []
  45. console.log(arr, arr.splice(3, 2, 'f'));
  46. //["a", "b", "c", "f"] []
  47. console.log(arr, arr.splice(3, 3, 'f'));
  48. //["a", "b", "c", "f"] []
  49. console.log(arr, arr.splice(3, 4, 'f'));
  50. //["a", "b", "c", "f"] []
  51. console.log(arr, arr.splice(true, false, 'f'));
  52. //["a", "f", "b", "c"] []
  53. console.log(arr, arr.splice(false, false, 'f'));
  54. //["f", "a", "b", "c"] []
  55. console.log(arr, arr.splice(false, true, 'f'));
  56. //["f", "b", "c"] ["a"]
  57. console.log(arr, arr.splice(undefined, undefined, 'f'));
  58. //["f", "a", "b", "c"] []
  59. console.log(arr, arr.splice(undefined, false, 'f'));
  60. //["f", "a", "b", "c"] []
  61. console.log(arr, arr.splice(undefined, true, 'f'));
  62. //["f", "b", "c"] ["a"]
  63. console.log(arr, arr.splice(null, null, 'f'));
  64. //["f", "a", "b", "c"] []
  65. console.log(arr, arr.splice(NaN, NaN, 'f'));
  66. //["f", "a", "b", "c"] []
  67. console.log(arr, arr.splice({}, {}, 'f'));
  68. //["f", "a", "b", "c"] []
  69. console.log(arr, arr.splice([], [], 'f'));
  70. //["f", "a", "b", "c"] []
  71. console.log(arr, arr.splice(function () {}, function () {}, 'f'));
  72. //["f", "a", "b", "c"] []
  73. console.log(new String('123'));
  74. //String {"123"}
  75. console.log(arr, arr.splice(new String('13'), new String('46'), 'f'));
  76. //["a", "b", "c", "f"] []
  77. //从123位开始 删除456位,然后在这个位置增加一个f
  78. console.log(arr, arr.splice(new String('123'), new String('456'), 'f'));
  79. //["a", "b", "c", "f"] []
  80. console.log(arr, arr.splice(new Number('123'), new Number('456'), 'f'));
  81. //["a", "b", "c", "f"] []
  82. console.log(arr, arr.splice(new Boolean(true), new Boolean(false), 'f'));
  83. //1 0 f -> ["a", "f", "b", "c"] []
  84. console.log(arr, arr.splice(new Boolean(true), new Boolean(true), 'f'));
  85. //1 1 f -> ["a", "f", "c"] ["b"]

写一个splice()的函数

  1. /**
  2. * myReverse()
  3. * @参数1 start 开始项的下标
  4. * @参数2 deleteCount 剪切长度(可选)
  5. * @参数3 item 要添加进数组的元素(可选)
  6. * @返回值1 被删除的元素组成的数组
  7. * @返回值2 被删除的元素组成的数组
  8. */
  9. var arr = ['a', 'b', 'c', 'e'];
  10. //在c和e中间添加d
  11. // arr.splice(正值/负值, 0, 'd')
  12. // //-1代表最后一项 -2代表倒数第二项 -3.....
  13. // arr.splice(-1, 0, 'd');
  14. // console.log(arr); //["a", "b", "c", "d", "e"]
  15. function splice(arr, index) {
  16. //原理:怎么实现指定位置(相应下标)?
  17. //此时返回的是元素下标
  18. return index += index >= 0 ? 0 : arr.length;
  19. //传入3
  20. //true: index = index + 0
  21. // index = 3 + 0
  22. //传入-1
  23. //false: index = index + arr.length
  24. // index = -1 + 4
  25. //传入-3
  26. //false: index = index + arr.length
  27. // index = -3 + 4
  28. }
  29. //打印数组长度
  30. console.log(arr.length); //4
  31. //打印下标
  32. console.log(splice(arr, 3)); //3
  33. console.log(splice(arr, -1)); //3
  34. console.log(splice(arr, -3)); //1
  35. //打印元素
  36. console.log(arr[splice(arr, -3)]); //b
  37. console.log(arr[splice(arr, -1)]); //e

Array.prototype.sort()

对数组的元素进行排序,并返回数组。

默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的

按照ASCII码来排序

  • 返回值

    • 排序后的数组。
  • 参数

    • compareFunction:用来指定按某种顺序进行排列的函数。
    • firstEl:第一个用于比较的元素。
    • secondEl:第二个用于比较的元素。
  1. //sort()
  2. var arr = [-1, -5, 8, 0, 2];
  3. arr.sort();
  4. console.log(arr); //升序:[-1, -5, 0, 2, 8]
  1. var arr = ['b', 'z', 'h', 'i', 'a'];
  2. arr.sort();
  3. console.log(arr); //升序:["a", "b", "h", "i", "z"]
  4. //返回排序以后的数组
  5. console.log(arr.sort()); //["a", "b", "h", "i", "z"]
  1. //sort()按照ASCII码来排列的
  2. var arr = [27, 49, 5, 7];
  3. arr.sort();
  4. console.log(arr); //不排序:[27, 49, 5, 7]

没有参数/返回值:

  1. var arr = ['a', 'b', 'c'];
  2. //var arr = [];
  3. console.log(arr.sort());
  4. //["a", "b", "c"]
  5. //[]

参数1/参数2/返回值:

  • 除了传入函数或undefined,返回值传入其他参数都报错
  1. //参数1/返回值:
  2. console.log(arr, arr.sort('d'));
  3. //Uncaught TypeError: The comparison function must be either a function or undefined
  4. console.log(arr, arr.sort(5));
  5. //Uncaught TypeError: The comparison function must be either a function or undefined
  6. console.log(arr, arr.sort(true));
  7. //Uncaught TypeError: The comparison function must be either a function or undefined
  8. console.log(arr, arr.sort(undefined));
  9. //["a", "b", "c"] (3) ["a", "b", "c"]
  10. console.log(arr, arr.sort(null));
  11. // Uncaught TypeError: The comparison function must be either a function or undefined
  12. console.log(arr, arr.sort(NaN));
  13. //Uncaught TypeError: The comparison function must be either a function or undefined
  14. console.log(arr, arr.sort(0));
  15. //Uncaught TypeError: The comparison function must be either a function or undefined
  16. console.log(arr, arr.sort(false));
  17. //Uncaught TypeError: The comparison function must be either a function or undefined
  18. console.log(arr, arr.sort({}));
  19. //Uncaught TypeError: The comparison function must be either a function or undefined
  20. console.log(arr, arr.sort([]));
  21. //Uncaught TypeError: The comparison function must be either a function or undefined
  22. console.log(arr, arr.sort(function () {}));
  23. //["a", "b", "c"] (3) ["a", "b", "c"]
  24. console.log(arr, arr.sort(new String('123')));
  25. //Uncaught TypeError: The comparison function must be either a function or undefined
  26. console.log(arr, arr.sort(new Number('123')));
  27. //Uncaught TypeError: The comparison function must be either a function or undefined
  28. console.log(arr, arr.sort(new Boolean(true)));
  29. //Uncaught TypeError: The comparison function must be either a function or undefined

解决只排序单位的方案

  1. //sort(函数) 函数可以自定义排序方法
  2. //1.必须携带两个参数
  3. //2.必须自定义返回值
  4. //3.如果返回值为负值,a就为前面 a < b
  5. //4.如果返回值为正值,b就为前面 a > b
  6. //5.如果返回值为0,保持不动
  7. //冒泡排序法
  8. //循环顺序
  9. //1.27比49
  10. //2.27比5
  11. //3.27比7
  12. //4.49比5
  13. //5.......
  14. //正值
  15. //27 49
  16. //5 27
  17. //7 27
  18. //5 49
  19. //7 49
  20. //5 7
  21. var arr = [27, 49, 5, 7];
  22. arr.sort(function (a, b) {
  23. //升序
  24. if (a > b) {
  25. return 1;
  26. } else {
  27. return -1;
  28. }
  29. //升序:这里也可以写为 return a - b;
  30. //降序:这里也可以写为 return b - a;
  31. //降序
  32. // if (a > b) {
  33. // return -1;
  34. // } else {
  35. // return 1;
  36. // }
  37. });
  38. console.log(arr); //[5, 7, 27, 49]
  39. // console.log(arr); //[49, 27, 7, 5]

随机排序(笔试题)

  1. var arr = [1, 2, 3, 4, 5, 6];
  2. //随机方法
  3. //Math.ramdom() -> 0 - 1; 开区间(不包括0/1)
  4. arr.sort(function (a, b) {
  5. var rand = Math.random();
  6. //0.5之前(50%几率)
  7. //0.5之后(50%几率)
  8. //大于0.5
  9. if (rand - 0.5 > 0) {
  10. return 1;
  11. //小于0.5
  12. } else {
  13. return -1;
  14. }
  15. //也可以这样写
  16. // return Math.random() - 0.5;
  17. });
  18. console.log(arr); //每次不一样的数组

排序且数组里数据为对象(笔试题)

  1. var arr = [
  2. //a项
  3. {
  4. son: 'Jenny',
  5. age: 18
  6. },
  7. //b项
  8. {
  9. son: 'Jone',
  10. age: 10
  11. },
  12. {
  13. son: 'Ben',
  14. age: 16
  15. },
  16. {
  17. son: 'Crytal',
  18. age: 3
  19. },
  20. {
  21. son: 'Lucy',
  22. age: 12
  23. }
  24. ];
  25. //希望根据age字段排序
  26. arr.sort(function (a, b) {
  27. if (a.age > b.age) {
  28. return 1;
  29. } else {
  30. return -1;
  31. }
  32. });
  33. console.log(arr);
  34. /**
  35. * (5) [{…}, {…}, {…}, {…}, {…}]
  36. 0: {son: "Crytal", age: 3}
  37. 1: {son: "Jone", age: 10}
  38. 2: {son: "Lucy", age: 12}
  39. 3: {son: "Ben", age: 16}
  40. 4: {son: "Jenny", age: 18}
  41. length: 5
  42. __proto__: Array(0)
  43. */

根据字符长度排序

  1. var arr = ['12345', '1', '1234', '12', '1234567'];
  2. //希望长度为准来排序
  3. arr.sort(function (a, b) {
  4. if (a.length > b.length) {
  5. return 1;
  6. } else {
  7. return -1;
  8. }
  9. //return a.length - b.length;
  10. });
  11. console.log(arr); //["1", "12", "1234", "12345", "1234567"]

Array.prototype.concat()

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

返回新的整合数组

  • 返回值

    • 新的 Array 实例。
  • 参数

    • valueN(可选):数组和/或值,将被合并到一个新的数组中。
  1. var arr1 = ['a', 'b', 'c'];
  2. var arr2 = ['d', 'e', 'f'];
  3. var arr3 = arr1.concat(arr2);
  4. var arr4 = arr2.concat(arr1);
  5. console.log(arr1); //["a", "b", "c"]
  6. console.log(arr2); //["d", "e", "f"]
  7. console.log(arr3); //["a", "b", "c", "d", "e", "f"]
  8. console.log(arr4); //["d", "e", "f", "a", "b", "c"]

参数/返回值:

  • 返回新的拼接后的数组
  1. console.log(arr, arr.concat('e'));
  2. //["a", "b", "c"]["a", "b", "c", "e"]
  3. console.log(arr, arr.concat(5));
  4. //["a", "b", "c"]["a", "b", "c", 5]
  5. console.log(arr, arr.concat(true));
  6. //["a", "b", "c"]["a", "b", "c", true]
  7. console.log(arr, arr.concat(undefined));
  8. //["a", "b", "c"]["a", "b", "c", undefined]
  9. console.log(arr, arr.concat(null));
  10. //["a", "b", "c"]["a", "b", "c", null]
  11. console.log(arr, arr.concat(NaN));
  12. //["a", "b", "c"]["a", "b", "c", NaN]
  13. console.log(arr, arr.concat(0));
  14. //["a", "b", "c"]["a", "b", "c", 0]
  15. console.log(arr, arr.concat(false));
  16. //["a", "b", "c"]["a", "b", "c", false]
  17. console.log(arr, arr.concat({}));
  18. //["a", "b", "c"]["a", "b", "c", {…}]
  19. console.log(arr, arr.concat([]));
  20. //["a", "b", "c"]["a", "b", "c"]
  21. console.log(arr, arr.concat(function () {}));
  22. //["a", "b", "c"]["a", "b", "c", ƒ]
  23. console.log(arr, arr.concat(new String('123')));
  24. //["a", "b", "c"]["a", "b", "c", String {"123"}]
  25. console.log(arr, arr.concat(new Number(123)));
  26. //["a", "b", "c"]["a", "b", "c", Number {123}]
  27. console.log(arr, arr.concat(new Boolean(true)));
  28. //["a", "b", "c"]["a", "b", "c", Boolean {true}]

Array.prototype.toString()

返回一个字符串,表示指定的数组及其元素。

  • 返回值

    • 一个表示指定的数组及其元素的字符串。
  • 参数

    • 没有

数组上的toString()

  1. //自动逗号分割字符串
  2. var arr = ['a', 'b', 'c'];
  3. console.log(arr.toString()); //a, b, c
  4. var arr2 = [1, 2, 3, 4];
  5. console.log(arr2.toString()); //1, 2, 3, 4

没有参数/返回值:

  1. var arr = ['a', 'b', 'c'];
  2. // console.log(arr, arr.toString());
  3. //["a", "b", "c"] "a,b,c"

参数/返回值:

  • 不管有没有传参都返回指定数组元素的字符串
  1. console.log(arr, arr.toString('e'));
  2. //["a", "b", "c"] "a,b,c"
  3. console.log(arr, arr.toString(5));
  4. //["a", "b", "c"] "a,b,c"
  5. console.log(arr, arr.toString(true));
  6. //["a", "b", "c"] "a,b,c"
  7. console.log(arr, arr.toString(undefined));
  8. //["a", "b", "c"] "a,b,c"
  9. console.log(arr, arr.toString(null));
  10. //["a", "b", "c"] "a,b,c"
  11. console.log(arr, arr.toString(NaN));
  12. //["a", "b", "c"] "a,b,c"
  13. console.log(arr, arr.toString(0));
  14. //["a", "b", "c"] "a,b,c"
  15. console.log(arr, arr.toString(false));
  16. //["a", "b", "c"] "a,b,c"
  17. console.log(arr, arr.toString({}));
  18. //["a", "b", "c"] "a,b,c"
  19. console.log(arr, arr.toString([]));
  20. //["a", "b", "c"] "a,b,c"
  21. console.log(arr, arr.toString(function () {}));
  22. //["a", "b", "c"] "a,b,c"
  23. console.log(arr, arr.toString(new String('123')));
  24. //["a", "b", "c"] "a,b,c"
  25. console.log(arr, arr.toString(new Number(123)));
  26. //["a", "b", "c"] "a,b,c"
  27. console.log(arr, arr.toString(new Boolean(true)));
  28. //["a", "b", "c"] "a,b,c"
  29. console.log(arr, arr.toString('&'));
  30. //["a", "b", "c"] "a,b,c"
  31. console.log(arr, arr.toString('-'));
  32. //["a", "b", "c"] "a,b,c"

Array.prototype.slice()

返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

  • 返回值

    • 一个含有被提取元素的新数组。
    • 不传参返回新的克隆数组
  • 参数

    • begin:从该索引开始提取原数组元素。

      • 如果省略 begin,则 slice 从索引 0 开始。
      • 如果 begin 超出原数组的索引范围,则会返回空数组。
    • end:在该索引处结束提取原数组元素。

      • 如果 end 被省略,则 slice 会一直提取到原数组末尾。
      • 如果 end 大于数组的长度,slice 也会一直提取到原数组末尾。

开区间和闭区间:

  • 包含本身就叫闭区间 [start, end]
  • 不包含本身就叫开区间 (start, end)
  1. var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
  2. //克隆数组
  3. var arr1 = arr.slice();
  4. console.log(arr1); //['a', 'b', 'c', 'd', 'e', 'f']
  1. //参数1:
  2. //这里参数里的1指代下标1 从该下标(包含)开始截取到最后
  3. var arr2 = arr.slice(1);
  4. console.log(arr2); //['b', 'c', 'd', 'e', 'f']
  1. //参数2:
  2. //结束元素的下标之前(不包括)
  3. var arr3 = arr.slice(1, 3);
  4. console.log(arr3); //['b', 'c']
  1. //负值
  2. //从该下标(包含)开始截取到结束元素的下标之前(不包括)
  3. var arr4 = arr.slice(-3, 5);
  4. console.log(arr4); //["d", "e"]
  5. var arr5 = arr.slice(-3, -2);
  6. console.log(arr5); //["d"]
  7. var arr6 = arr.slice(-3, -1);
  8. console.log(arr6); //["d", "e"]

没有参数/返回值:

  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.slice());
  3. //["a", "b", "c"] (3) ["a", "b", "c"]

当数组为空/返回值:

  1. var arr = [];
  2. console.log(arr, arr.slice());
  3. //[] []

参数1/返回值:

  • 传入参数大于等于0且小于数组长度,返回参数数值对应数量的数值元素
  • 传入参数大于数值长度,返回空数组
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.slice('e'));
  3. //["a", "b", "c"] (3) ["a", "b", "c"]
  4. console.log(arr, arr.slice(-1));
  5. //["a", "b", "c"]["c"]
  6. console.log(arr, arr.slice(0));
  7. //["a", "b", "c"] (3) ["a", "b", "c"]
  8. console.log(arr, arr.slice(1));
  9. //["a", "b", "c"] (2) ["b", "c"]
  10. console.log(arr, arr.slice(2));
  11. //["a", "b", "c"] ["c"]
  12. console.log(arr, arr.slice(3));
  13. //["a", "b", "c"] []
  14. console.log(arr, arr.slice(4));
  15. //["a", "b", "c"] []
  16. console.log(arr, arr.slice(true));
  17. //["a", "b", "c"] (2) ["b", "c"]
  18. console.log(arr, arr.slice(undefined));
  19. //["a", "b", "c"] (3) ["a", "b", "c"]
  20. console.log(arr, arr.slice(null));
  21. //["a", "b", "c"] (3) ["a", "b", "c"]
  22. console.log(arr, arr.slice(NaN));
  23. //["a", "b", "c"] (3) ["a", "b", "c"]
  24. console.log(arr, arr.slice(0));
  25. //["a", "b", "c"] (3) ["a", "b", "c"]
  26. console.log(arr, arr.slice(false));
  27. //["a", "b", "c"] (3) ["a", "b", "c"]
  28. console.log(arr, arr.slice({}));
  29. //["a", "b", "c"] (3) ["a", "b", "c"]
  30. console.log(arr, arr.slice([]));
  31. //["a", "b", "c"] (3) ["a", "b", "c"]
  32. console.log(arr, arr.slice(function () {}));
  33. //["a", "b", "c"] (3) ["a", "b", "c"]
  34. console.log(arr, arr.slice(new String('123')));
  35. //["a", "b", "c"] []
  36. console.log(arr, arr.slice(new Number(123)));
  37. //["a", "b", "c"] []
  38. console.log(arr, arr.slice(new Boolean(true)));
  39. //["a", "b", "c"] (2) ["b", "c"]
  40. console.log(arr, arr.slice(new Boolean(false)));
  41. //["a", "b", "c"] (3) ["a", "b", "c"]

参数2/返回值:

  • 传入参数2大于参数1,返回范围为参数1下标到参数2下标的元素数组
  • 传入参数2等于参数1,返回空数组
  • 传入参数2小于参数1,返回空数组
  • 传入参数2大于数值长度,根据参数1返回数组元素
  1. console.log(arr, arr.slice('e', 'f'));
  2. //["a", "b", "c"] []
  3. console.log(arr, arr.slice(-1, -1));
  4. //["a", "b", "c"] []
  5. console.log(arr, arr.slice(-1, 0));
  6. //["a", "b", "c"] []
  7. console.log(arr, arr.slice(-1, 1));
  8. //["a", "b", "c"] []
  9. console.log(arr, arr.slice(-1, 2));
  10. //["a", "b", "c"] []
  11. console.log(arr, arr.slice(-1, 3));
  12. //["a", "b", "c"] ["c"]
  13. console.log(arr, arr.slice(0, 0));
  14. //["a", "b", "c"] []
  15. console.log(arr, arr.slice(0, 1));
  16. //["a", "b", "c"] ["a"]
  17. console.log(arr, arr.slice(0, 2));
  18. //["a", "b", "c"] (2) ["a", "b"]
  19. console.log(arr, arr.slice(0, 3));
  20. //["a", "b", "c"] (3) ["a", "b", "c"]
  21. console.log(arr, arr.slice(1, 0));
  22. //["a", "b", "c"] []
  23. console.log(arr, arr.slice(1, 1));
  24. //["a", "b", "c"] []
  25. console.log(arr, arr.slice(1, 2));
  26. //["a", "b", "c"] ["b"]
  27. console.log(arr, arr.slice(1, 3));
  28. //["a", "b", "c"] (2) ["b", "c"]
  29. console.log(arr, arr.slice(2, 1));
  30. //["a", "b", "c"] []
  31. console.log(arr, arr.slice(2, 2));
  32. //["a", "b", "c"] []
  33. console.log(arr, arr.slice(2, 3));
  34. //["a", "b", "c"] ["c"]
  35. console.log(arr, arr.slice(3, 3));
  36. //["a", "b", "c"] []
  37. console.log(arr, arr.slice(true, true));
  38. // ["a", "b", "c"][]
  39. console.log(arr, arr.slice(true, false));
  40. // ["a", "b", "c"][]
  41. console.log(arr, arr.slice(false, true));
  42. // ["a", "b", "c"]["a"]
  43. console.log(arr, arr.slice(undefined, undefined));
  44. //["a", "b", "c"] ["a", "b", "c"]
  45. console.log(arr, arr.slice(null, null));
  46. //["a", "b", "c"] []
  47. console.log(arr, arr.slice(NaN, NaN));
  48. //["a", "b", "c"] []
  49. console.log(arr, arr.slice(false, false));
  50. //["a", "b", "c"] []
  51. console.log(arr, arr.slice({}, {}));
  52. //["a", "b", "c"] []
  53. console.log(arr, arr.slice([], []));
  54. //["a", "b", "c"] []
  55. console.log(arr, arr.slice(function () {}, function () {}));
  56. //["a", "b", "c"] []
  57. console.log(arr, arr.slice(new String('123'), new String('456')));
  58. //["a", "b", "c"] []
  59. console.log(arr, arr.slice(new Number(123), new Number(456)));
  60. //["a", "b", "c"] []
  61. console.log(arr, arr.slice(new Boolean(true), new Boolean(false)));
  62. ///["a", "b", "c"] []
  63. console.log(arr, arr.slice(new Boolean(false), new Boolean(true)));
  64. //["a", "b", "c"] ["a"]

Array.prototype.join()

将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。

  • 返回值

    • 一个所有数组元素连接的字符串。
    • 如果 arr.length 为0,则返回空字符串。
  • 参数

    • separator:指定一个字符串来分隔数组的每个元素。

没有传参/返回值:

  • 返回逗号隔开的字符串
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.join());
  3. //["a", "b", "c"] "a,b,c"

数组长度为0/返回值:

  1. var arr = [];
  2. console.log(arr, arr.join());
  3. //[] ""

参数/返回值:

  • 传入undefined, 返回逗号隔开的字符串
  • 传入[],返回没有逗号的字符串
  • 传入其他字符,返回其他字符隔开的字符串
  1. console.log(arr, arr.join('e'));
  2. //["a", "b", "c"] "aebec"
  3. console.log(arr, arr.join(5));
  4. //["a", "b", "c"] "a5b5c"
  5. console.log(arr, arr.join(true));
  6. //["a", "b", "c"] "atruebtruec"
  7. console.log(arr, arr.join(undefined));
  8. // ["a", "b", "c"] "a,b,c"
  9. console.log(arr, arr.join(null));
  10. //["a", "b", "c"] "anullbnullc"
  11. console.log(arr, arr.join(NaN));
  12. //["a", "b", "c"] "aNaNbNaNc"
  13. console.log(arr, arr.join(0));
  14. //["a", "b", "c"] "a0b0c"
  15. console.log(arr, arr.join(false));
  16. //["a", "b", "c"] "afalsebfalsec"
  17. console.log(arr, arr.join({}));
  18. //["a", "b", "c"] "a[object Object]b[object Object]c"
  19. console.log(arr, arr.join([]));
  20. //连逗号也去掉
  21. //["a", "b", "c"] "abc"
  22. console.log(arr, arr.join(function () {}));
  23. //["a", "b", "c"] "afunction () {}bfunction () {}c"
  24. console.log(arr, arr.join(new String('123')));
  25. //["a", "b", "c"] "a123b123c"
  26. console.log(arr, arr.join(new Number(123)));
  27. //["a", "b", "c"] "a123b123c"
  28. console.log(arr, arr.join(new Boolean(true)));
  29. //["a", "b", "c"] "atruebtruec"
  30. console.log(arr, arr.join('&'));
  31. //["a", "b", "c"] "a&b&c"
  32. console.log(arr, arr.join('-'));
  33. //["a", "b", "c"] "a-b-c"

Array.prototype.indexOf()

ECMAScript 2015 (6th Edition, ECMA-262)

返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

  1. const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
  2. console.log(beasts.indexOf('bison'));
  3. //1
  4. // start from index 2
  5. console.log(beasts.indexOf('bison', 2));
  6. //4
  7. console.log(beasts.indexOf('giraffe'));
  8. //-1

语法

  1. arr.indexOf(searchElement, fromIndex)

参数

  • searchElement:要查找的元素
  • fromIndex:开始查找的位置。

    • 如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。
    • 如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消
    • 如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。

返回值

首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1

注意:存在重复元素的情况indexOf()方法只返回第一个符合的元素索引

  1. //存在重复元素的情况,indexOf()方法只返回第一个符合的元素索引
  2. var arr2 = ['a', 'b', 'a', 'c'];
  3. console.log(arr2.indexOf('a')); //0
  1. var array = [2, 5, 9];
  2. array.indexOf(2); // 0
  3. array.indexOf(7); // -1
  4. array.indexOf(9, 2); // 2
  5. array.indexOf(2, -1); // -1
  6. array.indexOf(2, -3); // 0

找出指定元素出现的所有位置

  1. var indices = [];
  2. var array = ['a', 'b', 'a', 'c', 'a', 'd'];
  3. var element = 'a';
  4. var idx = array.indexOf(element);
  5. while (idx != -1) {
  6. indices.push(idx);
  7. idx = array.indexOf(element, idx + 1);
  8. }
  9. console.log(indices);
  10. // [0, 2, 4]

参数1/返回值:

  • 除了指定的元素,其余返回-1
  • 返回指定元素的索引
  • 参数为空返回-1
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.indexOf()); //["a", "b", "c"] -1
  3. console.log(arr, arr.indexOf(1)); //["a", "b", "c"] -1
  4. console.log(arr, arr.indexOf('abc')); //["a", "b", "c"] -1
  5. console.log(arr, arr.indexOf(true)); //["a", "b", "c"] -1
  6. console.log(arr, arr.indexOf(false)); //["a", "b", "c"] -1
  7. console.log(arr, arr.indexOf(undefined)); //["a", "b", "c"] -1
  8. console.log(arr, arr.indexOf(null)); //["a", "b", "c"] -1
  9. console.log(arr, arr.indexOf(NaN)); //["a", "b", "c"] -1
  10. console.log(arr, arr.indexOf(0)); //["a", "b", "c"] -1
  11. console.log(arr, arr.indexOf({})); //["a", "b", "c"] -1
  12. console.log(arr, arr.indexOf([])); //["a", "b", "c"] -1
  13. console.log(arr, arr.indexOf(function () {})); //["a", "b", "c"] -1
  14. console.log(arr, arr.indexOf(new String('abc'))); //["a", "b", "c"] -1
  15. console.log(arr, arr.indexOf(new Number(123))); //["a", "b", "c"] -1
  16. console.log(arr, arr.indexOf(new Boolean(true))); //["a", "b", "c"] -1
  17. console.log(arr, arr.indexOf('a')); //["a", "b", "c"] 0
  18. console.log(arr, arr.indexOf('b')); //["a", "b", "c"] 1
  19. console.log(arr, arr.indexOf('c')); //["a", "b", "c"] 2

参数2/返回值:

  • 除了指定的元素,其余返回-1
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.indexOf(1, 2)); //["a", "b", "c"] -1
  3. console.log(arr, arr.indexOf('abc', 'bcd')); //["a", "b", "c"] -1
  4. console.log(arr, arr.indexOf(true, false)); //["a", "b", "c"] -1
  5. console.log(arr, arr.indexOf(false, true)); //["a", "b", "c"] -1
  6. console.log(arr, arr.indexOf(undefined, undefined)); //["a", "b", "c"] -1
  7. console.log(arr, arr.indexOf(null, null)); //["a", "b", "c"] -1
  8. console.log(arr, arr.indexOf(NaN, NaN)); //["a", "b", "c"] -1
  9. console.log(arr, arr.indexOf(0, 0)); //["a", "b", "c"] -1
  10. console.log(arr, arr.indexOf({}, {})); //["a", "b", "c"] -1
  11. console.log(arr, arr.indexOf([], [])); //["a", "b", "c"] -1
  12. console.log(arr, arr.indexOf(function () {}, function () {})); //["a", "b", "c"] -1
  13. console.log(arr, arr.indexOf(new String('abc'), new String('bcd'))); //["a", "b", "c"] -1
  14. console.log(arr, arr.indexOf(new Number(123), new Number(456))); //["a", "b", "c"] -1
  15. console.log(arr, arr.indexOf(new Boolean(true), new Boolean(false))); //["a", "b", "c"] -1

返回索引值长度小于数组长度的元素索引值

  1. console.log(arr, arr.indexOf('a', -1)); //["a", "b", "c"] -1
  2. console.log(arr, arr.indexOf('a', 0)); //["a", "b", "c"] 0
  3. console.log(arr, arr.indexOf('a', 1)); //["a", "b", "c"] -1
  4. console.log(arr, arr.indexOf('a', 2)); //["a", "b", "c"] -1
  5. console.log(arr, arr.indexOf('a', 3)); //["a", "b", "c"] -1
  6. console.log(arr, arr.indexOf('b', -1)); //["a", "b", "c"] -1
  7. console.log(arr, arr.indexOf('b', 0)); //["a", "b", "c"] 1
  8. console.log(arr, arr.indexOf('b', 1)); //["a", "b", "c"] 1
  9. console.log(arr, arr.indexOf('b', 2)); //["a", "b", "c"] -1
  10. console.log(arr, arr.indexOf('b', 3)); //["a", "b", "c"] -1
  11. console.log(arr, arr.indexOf('c', -1)); //["a", "b", "c"] 2
  12. console.log(arr, arr.indexOf('c', 0)); //["a", "b", "c"] 2
  13. console.log(arr, arr.indexOf('c', 1)); //["a", "b", "c"] 2
  14. console.log(arr, arr.indexOf('c', 2)); //["a", "b", "c"] 2
  15. console.log(arr, arr.indexOf('c', 3)); //["a", "b", "c"] -1

Array.prototype.lastIndexOf()

ECMAScript 2015 (6th Edition, ECMA-262)

返回指定元素在数组中的最后一个的索引

  1. const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
  2. console.log(animals.lastIndexOf('Dodo'));
  3. //3
  4. console.log(animals.lastIndexOf('Tiger'));
  5. //1

语法

  1. arr.lastIndexOf(searchElement, fromIndex);

参数

  • searchElement:被查找的元素。
  • fromIndex:从此位置开始逆向查找。

    • 如果该值大于或等于数组的长度,则整个数组会被查找
    • 如果为负值,将其视为从数组末尾向前的偏移
    • 如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找

返回值

数组中该元素最后一次出现的索引,如未找到返回-1。

  1. var array = [2, 5, 9, 2];
  2. var index = array.lastIndexOf(2);
  3. // index is 3
  4. index = array.lastIndexOf(7);
  5. // index is -1
  6. index = array.lastIndexOf(2, 3);
  7. // index is 3
  8. index = array.lastIndexOf(2, 2);
  9. // index is 0
  10. index = array.lastIndexOf(2, -2);
  11. // index is 0
  12. index = array.lastIndexOf(2, -1);
  13. // index is 3

查找所有元素

  1. var indices = [];
  2. var array = ['a', 'b', 'a', 'c', 'a', 'd'];
  3. var element = 'a';
  4. var idx = array.lastIndexOf(element);
  5. while (idx != -1) {
  6. indices.push(idx);
  7. idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
  8. }
  9. console.log(indices);
  10. // [4, 2, 0];

参数1/返回值:

  • 除了指定的元素,其余返回-1
  • 返回指定元素的索引
  • 参数为空返回-1
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.lastIndexOf()); //["a", "b", "c"] -1
  3. console.log(arr, arr.lastIndexOf(1)); //["a", "b", "c"] -1
  4. console.log(arr, arr.lastIndexOf('abc')); //["a", "b", "c"] -1
  5. console.log(arr, arr.lastIndexOf(true)); //["a", "b", "c"] -1
  6. console.log(arr, arr.lastIndexOf(false)); //["a", "b", "c"] -1
  7. console.log(arr, arr.lastIndexOf(undefined)); //["a", "b", "c"] -1
  8. console.log(arr, arr.lastIndexOf(null)); //["a", "b", "c"] -1
  9. console.log(arr, arr.lastIndexOf(NaN)); //["a", "b", "c"] -1
  10. console.log(arr, arr.lastIndexOf(0)); //["a", "b", "c"] -1
  11. console.log(arr, arr.lastIndexOf({})); //["a", "b", "c"] -1
  12. console.log(arr, arr.lastIndexOf([])); //["a", "b", "c"] -1
  13. console.log(arr, arr.lastIndexOf(function () {})); //["a", "b", "c"] -1
  14. console.log(arr, arr.lastIndexOf(new String('abc'))); //["a", "b", "c"] -1
  15. console.log(arr, arr.lastIndexOf(new Number(123))); //["a", "b", "c"] -1
  16. console.log(arr, arr.lastIndexOf(new Boolean(true))); //["a", "b", "c"] -1
  17. console.log(arr, arr.lastIndexOf('a')); //["a", "b", "c"] 0
  18. console.log(arr, arr.lastIndexOf('b')); //["a", "b", "c"] 1
  19. console.log(arr, arr.lastIndexOf('c')); //["a", "b", "c"] 2

参数2/返回值:

  • 除了指定的元素,其余返回-1
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.lastIndexOf(1, 2)); //["a", "b", "c"] -1
  3. console.log(arr, arr.lastIndexOf('abc', 'bcd')); //["a", "b", "c"] -1
  4. console.log(arr, arr.lastIndexOf(true, false)); //["a", "b", "c"] -1
  5. console.log(arr, arr.lastIndexOf(false, true)); //["a", "b", "c"] -1
  6. console.log(arr, arr.lastIndexOf(undefined, undefined)); //["a", "b", "c"] -1
  7. console.log(arr, arr.lastIndexOf(null, null)); //["a", "b", "c"] -1
  8. console.log(arr, arr.lastIndexOf(NaN, NaN)); //["a", "b", "c"] -1
  9. console.log(arr, arr.lastIndexOf(0, 0)); //["a", "b", "c"] -1
  10. console.log(arr, arr.lastIndexOf({}, {})); //["a", "b", "c"] -1
  11. console.log(arr, arr.lastIndexOf([], [])); //["a", "b", "c"] -1
  12. console.log(arr, arr.lastIndexOf(function () {}, function () {})); //["a", "b", "c"] -1
  13. console.log(arr, arr.lastIndexOf(new String('abc'), new String('bcd'))); //["a", "b", "c"] -1
  14. console.log(arr, arr.lastIndexOf(new Number(123), new Number(456))); //["a", "b", "c"] -1
  15. console.log(arr, arr.lastIndexOf(new Boolean(true), new Boolean(false))); //["a", "b", "c"] -1
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.lastIndexOf('a', -1)); //["a", "b", "c"] 0
  3. console.log(arr, arr.lastIndexOf('a', 0)); //["a", "b", "c"] 0
  4. console.log(arr, arr.lastIndexOf('a', 1)); //["a", "b", "c"] 0
  5. console.log(arr, arr.lastIndexOf('a', 2)); //["a", "b", "c"] 0
  6. console.log(arr, arr.lastIndexOf('a', 3)); //["a", "b", "c"] 0
  7. console.log(arr, arr.lastIndexOf('b', -1)); //["a", "b", "c"] 1
  8. console.log(arr, arr.lastIndexOf('b', 0)); //["a", "b", "c"] -1
  9. console.log(arr, arr.lastIndexOf('b', 1)); //["a", "b", "c"] 1
  10. console.log(arr, arr.lastIndexOf('b', 2)); //["a", "b", "c"] 1
  11. console.log(arr, arr.lastIndexOf('b', 3)); //["a", "b", "c"] 1
  12. console.log(arr, arr.lastIndexOf('c', -1)); //["a", "b", "c"] 2
  13. console.log(arr, arr.lastIndexOf('c', 0)); //["a", "b", "c"] -1
  14. console.log(arr, arr.lastIndexOf('c', 1)); //["a", "b", "c"] -1
  15. console.log(arr, arr.lastIndexOf('c', 2)); //["a", "b", "c"] 2
  16. console.log(arr, arr.lastIndexOf('c', 3)); //["a", "b", "c"] 2

Array.prototype.find()

返回第一个满足条件的数组元素

find()的遍历效率是低于ES5数组扩展方法的

ESMAScript 2015 ES6

  1. const arr = [1, 2, 3, 4, 5];
  2. // const item = arr.find(item => item > 3);
  3. const item = arr.find(function (item) {
  4. return item > 3; //返回bool
  5. })
  6. console.log(item); //4
  1. /**
  2. * Array.prototype.find(function(item, index, arr){}, 参数2)
  3. * @item: 当前遍历的元素
  4. * @index: 当前遍历出的元素对应的下标
  5. * @arr: 当前的数组
  6. * @arguments[1]: 可选, 更改回调函数内部的this指向,默认指向window
  7. */
  8. //如果没有一个元素满足条件,返回undefined
  9. const arr1 = [1, 2, 3, 4, 5];
  10. const item1 = arr1.find(function (item) {
  11. return item > 5;
  12. })
  13. console.log(item1); //undefined
  14. //如果是引用值
  15. const arr2 = [{
  16. id: 1,
  17. name: 'zhangsan'
  18. },
  19. {
  20. id: 2,
  21. name: 'lisi'
  22. },
  23. {
  24. id: 3,
  25. name: 'wangwu'
  26. }
  27. ]
  28. const item2 = arr2.find(item => item.name === 'lisi');
  29. console.log(item2); //{id: 2, name: "lisi"}
  30. //返回的元素和数组对应下标的元素是同一个引用
  31. console.log(item2 === arr2[1]); //true
  32. //回调的参数(当前遍历的元素, 当前遍历出的元素对应的下标,当前的数组)
  33. //find的第二个参数是更改回调函数内部的this指向, 非严格模式环境下,this默认指向window, 在严格模式下不传入第二个参数,this为undefind,与严格模式相统一
  34. const item3 = arr2.find(function (item, index, arr) {
  35. console.log(item); //{id: 1, name: "zhangsan"} 某一项
  36. console.log(index); //0 索引值
  37. console.log(arr); //[{…}, {…}, {…}] 数组本身
  38. console.log(this); //{a: 1}
  39. }, {
  40. a: 1
  41. })
  1. //回调函数的返回值是布尔值,第一个返回true的对应数组元素作为find的返回值
  2. //find会遍历稀疏数组的空隙empty 具体遍历出的值,由undefined占位
  3. //ES5数组扩展方法指回遍历有值的索引
  4. const item = arr.find(function (item) {
  5. return item.id > 1;
  6. });
  7. console.log(item); //{id: 2, name: "lisi"}
  1. //在回调函数里对其进行元素的更改是不可以的
  2. //find()是不会更改数组的
  3. //虽然新增了元素,但是find()会在第一次执行回调函数的时候,拿到这个数组最初的索引范围
  4. const arr = [1, 2, 3, 4, 5];
  5. const item = arr.find(function (item) {
  6. // console.log('Gone');
  7. // item = item + 1;
  8. arr.push(6);
  9. console.log(item); //1 2 3 4 5
  10. })
  11. console.log(arr); //[1, 2, 3, 4, 5]
  1. const arr = [1, , 3, , , , 7, 8, 9];
  2. arr.find(function (item, index) {
  3. if (index === 0) {
  4. //删除了对应项,该项目位置不保留,在数据最后不上undefined
  5. arr.splice(1, 1); //1 3 undefined undefined undefined 7 8 9 undefined
  6. //删除该项的值并填入undefined
  7. // delete arr[2]; //1 undefined undefined undefined undefined undefined 7 8 9
  8. // 删除该项的值并填入undefined
  9. // arr.pop(); //1 undefined 3 undefined undefined undefined 7 8 undefined
  10. }
  11. console.log(item);
  12. })

写一个myFind()

  1. Array.prototype.myFind = function (cb) {
  2. if (this === null) {
  3. throw new TypeError('this is null');
  4. }
  5. if (typeof cb !== 'function') {
  6. throw new TypeError('Callback must be a function type');
  7. }
  8. var obj = Object(this),
  9. //保证为正整数
  10. len = obj.length >>> 0,
  11. arg2 = arguments[1],
  12. //下标
  13. step = 0;
  14. while (step < len) {
  15. var value = obj[step];
  16. if (cb.apply(arg2, [value, step, obj])) {
  17. return value;
  18. }
  19. step++;
  20. }
  21. return undefined;
  22. }
  23. const arr = [1, 2, 3, 4, 5];
  24. const item = arr.myFind(item => item > 3);
  25. console.log(item); //4

Array.prototype.findIndex()

返回第一个满足条件的数组元素的索引值

ECMASript 2015 ES6

查找元素对应的索引

  1. const arr = [1, 2, 3, 4, 5];
  2. //返回第一个满足条件的数组对应的元素下标
  3. const idx = arr.findIndex(item => item > 2);
  4. const item = arr.find(item => item > 2);
  5. console.log(idx); //2
  6. console.log(item); //3
  1. const arr = [1, 2, 3, 4, 5];
  2. //没有找到符合条件的元素返回 -1
  3. const idx2 = arr.findIndex(item => item > 5);
  4. console.log(idx2); //-1
  5. //数组长度为空的情况返回 -1
  6. const arr3 = [];
  7. const idx3 = arr3.findIndex(item => item > 2);
  8. console.log(idx3); //-1
  9. //稀疏数组是正常遍历空隙,空隙将会被填充为undefined
  10. //findIndex()如果回调返回了true,遍历就停止
  11. const arr4 = [, 2, , , , , , ];
  12. const idx4 = arr4.findIndex(function (item) {
  13. console.log(item); //undefined 2 1
  14. return item === 2;
  15. });
  16. console.log(idx4); //1
  1. var arr = [, 2, , , , , , ];
  2. //遍历7次
  3. const idx = arr.findIndex(function (item) {
  4. console.log('Gone');
  5. })
  6. //遍历有值的索引项
  7. arr.some(function (item) {
  8. console.log('Gone');
  9. return false;
  10. })
  11. //1次
  12. arr.every(function (item) {
  13. console.log('Gone');
  14. return true;
  15. })
  16. //1次
  17. arr.forEach(function (item) {
  18. console.log('Gone');
  19. })
  20. //1次
  21. arr.map(function (item) {
  22. console.log('Gone');
  23. })
  24. //1次
  25. arr.filter(function (item) {
  26. console.log('Gone');
  27. })
  28. //1次
  29. arr.reduce(function (item) {
  30. console.log('Gone');
  31. }, [])
  32. //对于单纯的遍历来说,遍历空隙是没有必要的,浪费性能的,对于寻找一个Index或某一项来说,都是有意义的
  1. /**
  2. * findIndex(function(item, index, arr){})
  3. * @argumengts[0]: function(){}
  4. * @argumengts[1]: {}
  5. * @item 遍历的当前数组元素
  6. * @index 元素对应的下标
  7. * @arr 源数组
  8. * @this 默认为window 如有第二个参数,会指向第二个参数 严格模式下this为undefined
  9. * @返回值 bool,遍历在某一次调用回调后返回true,停止
  10. */
  11. var arr = [1, 2, 3];
  12. const idx = arr.findIndex(function (item, index, arr) {
  13. console.log(item); //1
  14. console.log(index); //0
  15. console.log(arr); //[1, 2, 3]
  16. console.log(this); //window
  17. }, {
  18. a: 1
  19. })
  1. //回调函数内部是无法改变数组的元素值的
  2. var arr = [1, 2, 3];
  3. const idx = arr.findIndex(function (item) {
  4. item += 1;
  5. })
  6. console.log(arr); //[1, 2, 3]
  1. //虽然增加了元素,但是遍历只会进行3次
  2. //findIndex()在第一次调用回调函数的时候确认数组的范围
  3. var arr = [1, 2, 3];
  4. const idx = arr.findIndex(function (item) {
  5. arr.push(6);
  6. console.log('Gone');
  7. console.log(item); //1 2 3
  8. })
  9. console.log(arr); //[1, 2, 3, 6, 6, 6]
  1. var arr = [1, 2, 3];
  2. const idx = arr.findIndex(function (item, index) {
  3. // if (index === 0) {
  4. // //删除某一项
  5. // arr.splice(1, 1);
  6. // }
  7. // //仍然遍历3次
  8. // //最后一次补undefined
  9. // console.log(item); //1 3 undefined
  10. // // console.log(arr) [1, 3]
  11. // if (index === 0) {
  12. // //删除元素对应下标的值补undefined,实际数组中,对应下标变空隙empty
  13. // delete arr[1];
  14. // }
  15. // console.log(item); //1 undefined 3
  16. //console.log(arr) [1, empty, 3]
  17. if (index === 0) {
  18. //删除元素下标对应的值,补undefined,实际数组被删除了最后一项
  19. arr.pop();
  20. }
  21. console.log(item); // 1 2 undefined
  22. // console.log(arr); //[1, 2]
  23. })
  24. console.log(arr);

写一个findIndex()

  1. var arr = [1, 2, 3];
  2. Array.prototype.myFindIndex = function (cb) {
  3. if (this == null) {
  4. throw new TypeError('this is null');
  5. }
  6. if (typeof cb !== 'function') {
  7. throw new TypeError('Callback must be a function');
  8. }
  9. var obj = Object(this),
  10. len = obj.length >>> 0,
  11. arg2 = arguments[1],
  12. step = 0;
  13. while (step < len) {
  14. var value = obj[step];
  15. if (cb.apply(arg2, [value, step, obj])) {
  16. return step;
  17. }
  18. step++;
  19. }
  20. return -1;
  21. }
  22. const idx = arr.myFindIndex(function (item, index, arr) {
  23. return item > 2;
  24. })
  25. console.log(idx); //2

Array.prototype.sort()

ES3

对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的

  1. var arr = [5, 3, 1, 2, 6, 4];
  2. var newArr = arr.sort();
  3. console.log(newArr);
  4. //[1, 2, 3, 4, 5, 6]
  5. console.log(arr);
  6. //[1, 2, 3, 4, 5, 6]
  7. //返回原数组的引用,不进行数组引用赋值
  8. //原地算法
  9. //V8引擎性能:
  10. //arr.length <= 10 插入排序
  11. //arr.length > 10 快速排序
  12. //Mozilla 归并排序
  13. //Webkit c++ QSort 快速排序的理念
  14. console.log(newArr === arr); //true
  1. /**
  2. * sort并不会按照数字大小进行排序
  3. * toString() -> 数组元素 -> 字符串
  4. * DOMString -> UTF-16字符串实现 -> 映射到String -> 构建字符串
  5. * string -> UTF-16字符串 -> String/DOMString的实例
  6. * 按照UTF-16的编码顺序来进行排序
  7. */
  8. var arr = [5, 3, 1000, 1, 6];
  9. console.log(arr.sort());
  10. //[1, 1000, 3, 5, 6]
  11. var arr2 = ['b', 'x', 'i', 'm', 'a', 'd'];
  12. console.log(arr2.sort());
  13. //["a", "b", "d", "i", "m", "x"]
  14. var arr3 = [true, false];
  15. console.log(arr3.sort());
  16. //[false, true]
  1. /**
  2. * 为什么要转成字符串呢?
  3. * 如果是仅限一种类型的排序的话,sort功能性太弱
  4. * 用字符串和字符编码集结合在一起形成排序规则
  5. * 可排序的范围就大了
  6. */
  7. //字符串的逐个字符进行编码位的排序
  8. var arr = ['abc', 'aba'];
  9. console.log(arr.sort());
  10. //["aba", "abc"]
  1. //sort 一个参数(可选)
  2. //compareFunction 比较函数方法
  3. //compareFunction 自己写一个排序规则
  4. //FirElem
  5. //SecElem
  6. var arr = [5, 1, 2, 4, 6, 3, 3];
  7. console.log(arr.sort(function (a, b) {
  8. //没有写排序规则,不进行任何排序操作
  9. //a => 1 b => 5
  10. // console.log(a, b);
  11. //return 负值 a就排在b前面
  12. //return 正数 b就排在a前面
  13. //return 0- a与b不进行排序操作
  14. // if (a < b) {
  15. // return -1;
  16. // }
  17. // if (a > b) {
  18. // return 1;
  19. // }
  20. // if (a === b) {
  21. // return 0;
  22. // }
  23. //纯数字比较
  24. // return a - b;
  25. // return b - a;
  26. // return a === b;
  27. // return -1;
  28. // return 1;
  29. // return 0;
  30. //compareFunction 必须对相同的输入有相同返回结果,结果是不确定
  31. // if (Math.random() > 0, 5) {
  32. // return 1;
  33. // }
  34. // if (Math.random() > 0, 5) {
  35. // return -1;
  36. // }
  37. }));
  1. //非ASCII字符串排序
  2. var arr = ['我', '爱', '你'];
  3. console.log(arr.sort((a, b) => {
  4. return a.localeCompare(b);
  5. }));
  6. //["爱", "你", "我"]
  1. //写法一
  2. var arr = ['zhangsan', 'Datian', 'Mike', 'tony'];
  3. console.log(arr.sort(function (a, b) {
  4. var _a = a.toLowerCase(),
  5. _b = b.toLowerCase();
  6. if (_a < _b) {
  7. return -1;
  8. }
  9. if (_a > _b) {
  10. return 1;
  11. }
  12. return 0;
  13. }));
  14. //["Datian", "Mike", "tony", "zhangsan"]
  15. //写法二
  16. //映射方法
  17. var arr2 = ['zhangsan', 'Datian', 'Mike', 'tony'];
  18. var newArr = arr2.map(function (item, index) {
  19. var it = {
  20. index,
  21. value: item.toLowerCase()
  22. }
  23. return it;
  24. });
  25. newArr.sort(function (a, b) {
  26. if (a.value > b.value) {
  27. return 1;
  28. }
  29. if (a.value < b.value) {
  30. return -1;
  31. }
  32. return 0;
  33. })
  34. // console.log(newArr);
  35. var res = newArr.map(function (item) {
  36. return arr2[item.index];
  37. })
  38. console.log(res);
  39. //["Datian", "Mike", "tony", "zhangsan"]

Array.prototype.fill()

ECMASript 2015 ES6

该方法实际上根据下标范围内的元素覆盖填充新的值

返回值:新修改后的数组

  1. //Array.prototype.fill() ECMASript 2015 ES6
  2. /**
  3. * fill(value, start, end);
  4. * @value: 可选 默认全部填充undefined
  5. * @start: 可选 默认为0
  6. * @end: 可选 默认为数组长度
  7. */
  8. //[2, 4)
  9. const arr1 = [1, 2, 3, 4, 5];
  10. const newArr1 = arr1.fill('a', 2, 4);
  11. console.log(newArr1); //[1, 2, "a", "a", 5]
  12. //[2, end)
  13. //newArr就是原数组的引用
  14. const arr2 = [1, 2, 3, 4, 5];
  15. const newArr2 = arr2.fill('b', 2, 5);
  16. console.log(newArr2); //[1, 2, "b", "b", "b"]
  17. // console.log(arr === newArr); //true
  18. //[2, end)
  19. const arr3 = [1, 2, 3, 4, 5];
  20. const newArr3 = arr3.fill('c', 2);
  21. console.log(newArr3); //[1, 2, "c", "c", "c"]
  22. //[0, end)
  23. const arr4 = [1, 2, 3, 4, 5];
  24. const newArr4 = arr4.fill('d');
  25. console.log(newArr4); //["d", "d", "d", "d", "d"]
  26. //[-4 + len, -2 + len) -> [1, 3)
  27. const arr5 = [1, 2, 3, 4, 5];
  28. const newArr5 = arr5.fill('e', -4, -2);
  29. console.log(newArr5); //[1, "e", "e", 4, 5]
  30. //全部覆盖undefied
  31. const arr6 = [1, 2, 3, 4, 5];
  32. const newArr6 = arr6.fill();
  33. console.log(newArr6); //[undefined, undefined, undefined, undefined, undefined]
  34. //start === end
  35. //end 为开区间没办法选
  36. const arr7 = [1, 2, 3, 4, 5];
  37. const newArr7 = arr7.fill('f', 1, 1);
  38. console.log(newArr7); //[1, 2, 3, 4, 5]
  39. //start end 非数字 不变
  40. const arr8 = [1, 2, 3, 4, 5];
  41. const newArr8 = arr8.fill('g', 'a', 'b');
  42. console.log(newArr8); //[1, 2, 3, 4, 5]
  43. //start 非数字
  44. //end 数字
  45. //[0, 4]
  46. const arr9 = [1, 2, 3, 4, 5];
  47. const newArr9 = arr9.fill('g', 'a', 4);
  48. console.log(newArr9); //["g", "g", "g", "g", 5]
  49. //start end NaN 不变
  50. const arr10 = [1, 2, 3, 4, 5];
  51. const newArr10 = arr10.fill('g', NaN, NaN);
  52. console.log(newArr10); //[1, 2, 3, 4, 5]
  53. //start NaN
  54. //end 数字
  55. //[0, 4]
  56. const arr11 = [1, 2, 3, 4, 5];
  57. const newArr11 = arr11.fill('h', NaN, 4);
  58. console.log(newArr11); //["h", "h", "h", "h", 5]
  59. //start null
  60. //end null
  61. //不变
  62. const arr12 = [1, 2, 3, 4, 5];
  63. const newArr12 = arr12.fill('i', null, null);
  64. console.log(newArr12); //[1, 2, 3, 4, 5]
  65. //start undefined
  66. //end undefined
  67. //全部覆盖
  68. const arr13 = [1, 2, 3, 4, 5];
  69. const newArr13 = arr13.fill('j', undefined, undefined);
  70. console.log(newArr13); //["j", "j", "j", "j", "j"]
  71. //start 数字
  72. //end undefined
  73. //正常覆盖
  74. const arr14 = [1, 2, 3, 4, 5];
  75. const newArr14 = arr14.fill('j', 1, undefined);
  76. console.log(newArr14); //[1, "j", "j", "j", "j"]
  77. //start undefined
  78. //end 数字
  79. //正常覆盖
  80. const arr15 = [1, 2, 3, 4, 5];
  81. const newArr15 = arr15.fill('j', undefined, 4);
  82. console.log(newArr15); //["j", "j", "j", "j", 5]

无论数字,NaNnull,结果都是一样,undefined相当于没有填写

  1. //fill()根据length填充数量
  2. //Array.prototype.fill.call(this, value);
  3. const newObj = Array.prototype.fill.call({
  4. length: 3
  5. }, 4);
  6. console.log(newObj); //{0: 4, 1: 4, 2: 4, length: 3}
  1. //创建类数组方法
  2. function makeArrayLike(arr) {
  3. //将数组变为类数组
  4. var arrLike = {
  5. length: arr.length,
  6. push: [].push,
  7. splice: [].splice
  8. }
  9. arr.forEach(function (item, index) {
  10. [].fill.call(arrLike, item, index, index + 1);
  11. });
  12. return arrLike;
  13. }
  14. const newObj = makeArrayLike([
  15. 'a',
  16. 'b',
  17. 'c',
  18. 'd',
  19. 'e'
  20. ]);
  21. console.log(newObj);
  22. /**
  23. * Object(5) ["a", "b", "c", "d", "e", push: ƒ, splice: ƒ]
  24. * 0: "a"
  25. * 1: "b"
  26. * 2: "c"
  27. * 3: "d"
  28. * 4: "e"
  29. * length: 5
  30. * push: ƒ push()
  31. * splice: ƒ splice()
  32. * __proto__: Object
  33. */

写一个myFill()方法

  1. //fill()实现过程
  2. Array.prototype.myFill = function () {
  3. var value = arguments[0] || undefined,
  4. //正负整数
  5. start = arguments[1] >> 0,
  6. end = arguments[2];
  7. if (this === null) {
  8. throw new TypeError('This is null or not defined');
  9. }
  10. //包装为对象,保证为对象类型
  11. var obj = Object(this),
  12. //保证为正整数
  13. len = obj.length >>> 0;
  14. start = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
  15. end = end === undefined ? len : end >> 0;
  16. end = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
  17. while (start < end) {
  18. obj[start] = value;
  19. start++;
  20. }
  21. return obj;
  22. }
  23. var arr = [1, 2, 3, 4, 5];
  24. const newArr = arr.myFill('a', 2, 4);
  25. console.log(newArr); //[1, 2, "a", "a", 5]

Array.prototype.includes()

ECMAScript2016 ES7

用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false

  1. //认识这个方法
  2. /**
  3. * Array.prototype.includes()
  4. * 查询数组内是否包含某个元素
  5. * @arguments[0] target
  6. * @arguments[1] fromIndex 默认值为0
  7. * @返回值 布尔值
  8. */
  9. const arr = [1, 2, 3, 4, 5];
  10. console.log(arr.includes(3)); //true
  11. console.log(arr.includes(6)); //false
  1. //特殊性
  2. const arr = ['1', 'a', 3, 4, 5];
  3. /**
  4. * 区分字符串数字与数字
  5. * 区分大小写
  6. */
  7. console.log(arr.includes(1)); //false
  8. console.log(arr.includes('A')); //false
  1. //include是区分大小写的
  2. var str = 'abcde';
  3. console.log(str.includes('c')); //true
  4. console.log(str.includes('f')); //false
  5. console.log(str.includes('C')); //false
  1. //includes是有第二个参数的
  2. //arr.includes(5, fromIndex)
  3. //fromIndex 默认值为0
  4. //arr.includes(5, 从下标开始)
  5. //没传参数直接返回false
  6. var arr = [1, 2, 3, 4, 5];
  7. console.log(arr.includes(5, 3)); //true
  8. console.log(arr.includes(3, 3)); //false
  9. console.log(arr.includes(2)); //true
  10. console.log(arr.includes()); //false
  11. console.log(arr.includes.length); //1
  1. //负数
  2. //arr.length + (-2) 包含fromIndex
  3. //formIndex >= arr.length -> return false 不会对数组进行搜素
  4. //arr.length + (-6) = -1 < 0 整个数组都会搜素 从0开始
  5. console.log(arr.includes(3, -3)); //true
  6. console.log(arr.includes(3, 5)); //false
  7. console.log(arr.includes(3, -6)); //true
  1. //零值相等 SAME-VALUE-ZERO
  2. var arr = [0, 1, 2, 3, 4, 5];
  3. console.log(arr.includes(0)); //true
  4. console.log(arr.includes(-0)); //true
  5. console.log(arr.includes(+0)); //true
  1. //除了数组和字符串,其他类型的数据使用includes
  2. //includes 通用方法 调用者不一定非要是数组和对象 -> this 不一定是数组和对象
  3. //包装一下1
  4. console.log(Array.prototype.includes.call(1, 'a')); //false
  5. console.log([].includes.call(true, 'a')); //false
  6. console.log([].includes.call({0: 'a'}, 'a')); //false
  7. console.log([].includes.call({0: 'a',length: 1}, 'a')); //true

实现myIncludes()方法

  1. Array.prototype.myIncludes = function (value) {
  2. if (this == null) {
  3. throw new TypeError('this is null');
  4. }
  5. var fromIndex = arguments[1],
  6. obj = Object(this),
  7. len = obj.length >>> 0;
  8. if (len === 0) {
  9. return false;
  10. }
  11. //位或
  12. //如果为undefined 赋值为0
  13. fromIndex = fromIndex | 0;
  14. fromIndex = Math.max(fromIndex >= 0 ? fromIndex : len + fromIndex, 0);
  15. while (fromIndex < len) {
  16. if (obj[fromIndex] === value) {
  17. return true;
  18. }
  19. fromIndex++;
  20. }
  21. return false;
  22. }
  23. var arr = [1, 2, 3, 4, 5];
  24. console.log(arr.myIncludes(5, 3)); //true
  25. console.log(arr.myIncludes(3, 3)); //false
  26. console.log(arr.myIncludes(2)); //true
  27. console.log(arr.myIncludes()); //false
  28. console.log(arr.myIncludes.length); //1
  29. console.log(arr.myIncludes(3, -3)); //true
  30. console.log(arr.myIncludes(3, 5)); //false
  31. console.log(arr.myIncludes(3, -6)); //true

Array.prototype.copyWithin()

浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。

  1. //ES2015(ES6)
  2. //arr.copyWithin(target, start, end)
  3. //替换下标为0的元素
  4. //从3-4替换第0位元素
  5. //1.3-4 [3, 4)
  6. const arr = [1, 2, 3, 4, 5];
  7. const newArr = arr.copyWithin(0, 3, 4);
  8. console.log(newArr); //[4, 2, 3, 4, 5]
  9. //2.target 从 ...
  10. //3.end > len - 1 取到末尾
  11. const arr2 = [1, 2, 3, 4, 5];
  12. const newArr2 = arr2.copyWithin(0, 3, 5);
  13. console.log(newArr2); //[4, 5, 3, 4, 5]
  14. //4.target > len - 1 不发生任何替换
  15. const arr3 = [1, 2, 3, 4, 5];
  16. const newArr3 = arr3.copyWithin(5, 1, 5);
  17. console.log(newArr3); //[1, 2, 3, 4, 5]
  18. //5.target > start 正常替换
  19. const arr4 = [1, 2, 3, 4, 5];
  20. const newArr4 = arr4.copyWithin(3, 1, 3);
  21. console.log(newArr4); //[1, 2, 3, 2, 3]
  22. //6.start或end是负数 start + len ; end + len(0 2 4)
  23. const arr5 = [1, 2, 3, 4, 5];
  24. const newArr5 = arr5.copyWithin(0, -3, -1);
  25. console.log(newArr5); //[3, 4, 3, 4, 5]
  26. //7.如果没有start 取整个数组的元素
  27. //copyWithin()是不改变数组长度
  28. const arr6 = [1, 2, 3, 4, 5];
  29. const newArr6 = arr6.copyWithin(3);
  30. console.log(newArr6); //[1, 2, 3, 1, 2]
  31. //7.返回的是原数组引用
  32. //copyWithin()是不改变数组长度
  33. const arr7 = [1, 2, 3, 4, 5];
  34. const newArr7 = arr7.copyWithin(1, 3);
  35. console.log(newArr7); //[1, 4, 5, 4, 5]
  36. console.log(newArr7 === arr7); //true
  37. //memcpy -> 移动数组元素
  38. //过程一 复制元素集合
  39. //过程二 全选target及符合复制的元素集合的长度的元素再粘贴
  1. var obj = {
  2. 0: 1,
  3. 1: 2,
  4. 2: 3,
  5. 3: 4,
  6. 4: 5,
  7. length: 5
  8. }
  9. //对象下没有copyWithin()方法,用call()方法借用
  10. //this不一定非要指向数组, 可以指向一个对象
  11. const newObj = [].copyWithin.call(obj, 0, 2, 4);
  12. console.log(newObj);
  13. //同一引用
  14. console.log(obj === newObj); //true
  15. /**
  16. * console.log(newObj);
  17. * {
  18. 2: 3,
  19. 3: 4,
  20. 2: 3,
  21. 3: 4,
  22. 4: 5,
  23. length: 5
  24. }
  25. */

写一个myCopyWithin()方法

  1. /**
  2. * @target参数: 必填
  3. * @start参数: 选填
  4. * @end参数: 选填
  5. */
  6. Array.prototype.myCopyWithin = function (target) {
  7. if (this == null) {
  8. throw new TypeError('this is null or not defined');
  9. }
  10. //包装一下this防止是原始值
  11. var obj = Object(this),
  12. //保证length为正整数 右位移为0
  13. len = obj.length >>> 0,
  14. start = arguments[1],
  15. end = arguments[2],
  16. count = 0,
  17. //方向
  18. dir = 1;
  19. //保证target为正整数
  20. target = target >> 0;
  21. //target 小于0 找最大值 大于等于0 取最小值
  22. //Math.max(len + target, 0) 谁大取谁
  23. target = target < 0 ? Math.max(len + target, 0) : Math.min(target, len);
  24. //保证start存在,存在给正整数,否则为0
  25. start = start ? start >> 0 : 0;
  26. //负值找最大值
  27. start = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
  28. //保证end存在,存在给正整数,否则为0
  29. end = end ? end >> 0 : len;
  30. //负值找最大值
  31. end = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
  32. //取值范围
  33. count = Math.min(end - start, len - target);
  34. if (start < target && target < (start + count)) {
  35. dir = -1;
  36. start += count - 1;
  37. target += count - 1;
  38. }
  39. while (count > 0) {
  40. if (start in obj) {
  41. obj[target] = obj[start];
  42. } else {
  43. delete obj[target];
  44. }
  45. start += dir;
  46. target += dir;
  47. count--;
  48. }
  49. return obj;
  50. }
  51. const arr = [1, 2, 3, 4, 5];
  52. const newArr = arr.myCopyWithin(0, 3, 4);
  53. console.log(newArr); //[4, 2, 3, 4, 5]

Array.prototype.entries()

返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。

ES6新增

  1. const arr = [1, 2, 3, 4, 5];
  2. const _ = arr.entries();
  3. console.log(_);
  4. //Array Iterator {} 返回的是数组的迭代器对象
  5. const it = arr.entries();
  6. //next() -> {value:[index, item], done: ?}
  7. console.log(it.next()); //{value: [0, 1], done: false}
  8. console.log(it.next()); //{value: [1, 2], done: false}
  9. console.log(it.next()); //{value: [2, 3], done: false}
  10. console.log(it.next()); //{value: [3, 4], done: false}
  11. console.log(it.next()); //{value: [4, 5], done: false}
  12. console.log(it.next()); //{value: undefined, done: true}
  1. //for in 遍历对象
  2. for (let key in o) {
  3. console.log(key, o[key]); //a 1 b 2 c 3
  4. }
  5. //for of 遍历数组
  6. for (let v of arr) {
  7. console.log(v); //1 2 3 4 5
  8. }
  1. //遍历数组迭代的对象
  2. for (let v of it) {
  3. console.log(v); //1 2 3 4 5
  4. }
  5. /**
  6. * console.log(v):
  7. * (2) [0, 1]
  8. * (2) [1, 2]
  9. * (2) [2, 3]
  10. * (2) [3, 4]
  11. * (2) [4, 5]
  12. */
  1. //拿到下标和对应的值
  2. for (let collection of it) {
  3. const [i, v] = collection;
  4. console.log(i, v);
  5. }
  6. /**
  7. * console.log(i, v):
  8. * 0 1
  9. * 1 2
  10. * 2 3
  11. * 3 4
  12. * 4 5
  13. */
  1. //数组实际上就是一个特殊的对象,key键名是一个从0开始有序递增的数字
  2. //按顺序对应上数组的每一个元素
  3. //类数组
  4. var o = {
  5. 0: 1,
  6. 1: 2,
  7. 2: 3,
  8. length: 3,
  9. [Symbol.iterator]: Array.prototype[Symbol.iterator]
  10. }
  11. //通过属性是否继承了Array.prototype[Symbol.iterator]
  12. //for of 可以遍历可迭代对象
  13. for (let v of o) {
  14. console.log(v); //Uncaught TypeError: o is not iterable 不是可迭代对象
  15. console.log(v); //加上[Symbol.iterator]属性后遍历出 1 2 3
  16. }
  1. //next()运行案例
  2. const arr = [1, 2, 3, 4, 5];
  3. const it = arr.entries();
  4. var newArr = [];
  5. for (var i = 0; i < arr.length + 1; i++) {
  6. var item = it.next();
  7. // console.log(item.value);
  8. !item.done && (newArr[i] = item.value);
  9. }
  10. console.log(newArr);
  11. /**
  12. * console.log(newArr):
  13. * (5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
  14. * 0: (2) [0, 1]
  15. * 1: (2) [1, 2]
  16. * 2: (2) [2, 3]
  17. * 3: (2) [3, 4]
  18. * 4: (2) [4, 5]
  19. * length: 5
  20. * __proto__: Array(0)
  21. */
  1. //二维数组排序案例
  2. const newArr = [
  3. [56, 23],
  4. [56, 34, 100, 1],
  5. [123, 234, 12]
  6. ];
  7. function sortArr(arr) {
  8. //生成一个迭代器对象
  9. var _it = arr.entries(),
  10. _doNext = true;
  11. while (_doNext) {
  12. var _r = _it.next();
  13. if (!_r.done) {
  14. _r.value[1].sort(function (a, b) {
  15. return a - b;
  16. });
  17. _doNext = true;
  18. } else {
  19. _doNext = false;
  20. }
  21. }
  22. return arr;
  23. }
  24. console.log(sortArr(newArr));
  25. /**
  26. * (3) [Array(2), Array(4), Array(3)]
  27. * 0: (2) [23, 56]
  28. * 1: (4) [1, 34, 56, 100]
  29. * 2: (3) [12, 123, 234]
  30. * length: 3
  31. * __proto__: Array(0)
  32. */

Array.prototype.flat()

ECMAScript2019

按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

参数情况:

  1. //flag 扁平化 多维数组 -> 一维数组
  2. //针对数组
  3. //[1,2,3,4,5,[6,7]]
  4. const arr = [0, 1, [2, 3], 4, 5];
  5. const newArr = arr.flat();
  6. console.log(newArr); //[0, 1, 2, 3, 4, 5]
  7. //返回一个新的数组,将二维数组转化成一维数组
  8. console.log(newArr === arr); //false
  1. //三维数组
  2. //参数:结构深度 默认为1,向数组内部深入一层
  3. //flat()默认情况下参数是1 -> 向内深入一层
  4. const arr = [0, 1, [2, [3, 4], 5], 6];
  5. const newArr = arr.flat(1);
  6. console.log(newArr); //[0, 1, 2, Array(2), 5, 6]
  7. //flat()参数是2 -> 向内深入2层
  8. const arr2 = [0, 1, [2, [3, 4], 5], 6];
  9. const newArr2 = arr2.flat(2);
  10. console.log(newArr2); //[0, 1, 2, 3, 4, 5, 6]
  1. //多维数组
  2. //参数: Infinity 正无穷 深度结构 无穷大的设置
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. const newArr = arr.flat(Infinity);
  5. console.log(newArr); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. //参数为负数情况不做任何扁平化处理的
  2. const arr = [0, 1, [2, [3, 4], 5], 6];
  3. const newArr = arr.flat(-2);
  4. console.log(newArr); //[0, 1, Array(3), 6]
  1. //数字字符串 -> Number() -> 数字类型
  2. const arr = [0, 1, [2, [3, 4], 5], 6];
  3. const newArr = arr.flat('a');
  4. console.log(newArr); //[0, 1, Array(3), 6]
  5. const arr2 = [0, 1, [2, [3, 4], 5], 6];
  6. const newArr2 = arr2.flat('3');
  7. console.log(newArr2); //[0, 1, 2, 3, 4, 5, 6]
  1. //参数为负数0,不做任何扁平化处理的,数字必须从1开始填写,直到Infinity
  2. const arr = [0, 1, [2, [3, 4], 5], 6];
  3. const newArr = arr.flat(0);
  4. console.log(newArr); //[0, 1, Array(3), 6]
  1. //bool -> Number() -> 数字类型
  2. const arr = [0, 1, [2, [3, 4], 5], 6];
  3. const newArr = arr.flat(false); //0
  4. console.log(newArr); //[0, 1, Array(3), 6]
  5. //bool -> Number() -> 数字类型
  6. const arr2 = [0, 1, [2, [3, 4], 5], 6];
  7. const newArr2 = arr2.flat(true); //1
  8. console.log(newArr2); //[0, 1, 2, Array(2), 5, 6]

稀疏数组情况:

  1. //剔除所有的数组空隙empty
  2. const arr = [1, , [2, , [3, 4, , 5, , , 6, [7, , , 8, 9, , [0]]]]];
  3. const newArr = arr.flat(Infinity);
  4. console.log(newArr); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
  1. var a = 1,
  2. b = [2, 3],
  3. c = [3, 4];
  4. //concat 是可以放入多个数组元素或者其他数组
  5. const newArr = b.concat(a);
  6. console.log(newArr); //[2, 3, 1]
  7. const newArr2 = b.concat(a, c);
  8. console.log(newArr2); //[2, 3, 1, 3, 4]

浅扁平化实现:

  1. //浅扁平化实现
  2. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  3. //reduce() 归纳
  4. function shallowFlat(arr) {
  5. return arr.reduce(function (prev, current) {
  6. return prev.concat(current);
  7. }, [])
  8. }
  9. console.log(shallowFlat(arr));
  10. //[0, 1, 2, Array(3)]
  1. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  2. function shallowFlat(arr) {
  3. //展开数组
  4. return [].concat(...arr);
  5. }
  6. console.log(shallowFlat(arr));
  7. //[0, 1, 2, Array(3)]

深扁平化实现:

  1. //方法一
  2. //reduce + concat + isArray + 递归
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. Array.prototype.deepFlat = function () {
  5. var arr = this,
  6. deep = arguments[0] !== Infinity ? arguments[0] >>> 0 : Infinity;
  7. return deep > 0 ? arr.reduce(function (prev, current) {
  8. return prev.concat(Array.isArray(current) ? current.deepFlat(deep - 1) : current)
  9. }, []) : arr;
  10. }
  11. console.log(arr.deepFlat(Infinity));
  12. // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. //方法二
  2. //forEach + isArray + push + 递归
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. Array.prototype.deepFlat = function () {
  5. var arr = this,
  6. deep = arguments[0] !== Infinity ? arguments[0] >>> 0 : Infinity,
  7. res = [];
  8. (function _(arr, deep) {
  9. //数组扩展方法是会剔除empty
  10. arr.forEach(function (item) {
  11. if (Array.isArray(item) && deep > 0) {
  12. //递归
  13. _(item, deep - 1);
  14. } else {
  15. res.push(item);
  16. }
  17. })
  18. })(arr, deep);
  19. return res;
  20. }
  21. console.log(arr.deepFlat(Infinity));
  22. // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. //方法三
  2. //for of + isArray + push 去掉empty
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. Array.prototype.deepFlat = function () {
  5. var arr = this,
  6. deep = arguments[0] !== Infinity ? arguments[0] >>> 0 : Infinity,
  7. res = [];
  8. (function _(arr, deep) {
  9. for (var item of arr) {
  10. if (Array.isArray(item) && deep > 0) {
  11. _(item, deep - 1);
  12. } else {
  13. //判断empty 用void 0
  14. item !== void 0 && res.push(item);
  15. }
  16. }
  17. })(arr, deep);
  18. return res;
  19. }
  20. console.log(arr.deepFlat(Infinity));
  21. // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. //方法四
  2. //stack pop + push (重要)
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. Array.prototype.deepFlat = function () {
  5. var arr = this,
  6. stack = [...arr],
  7. res = [];
  8. //直到stack.length = 0
  9. while (stack.length) {
  10. //返回删除的最后一项
  11. const popItem = stack.pop();
  12. if (Array.isArray(popItem)) {
  13. //如果为数组
  14. //展开放入数组里
  15. stack.push(...popItem);
  16. } else {
  17. res.push(popItem);
  18. }
  19. }
  20. return res.reverse();
  21. }
  22. console.log(arr.deepFlat(Infinity));
  23. // // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. //方法五
  2. //纯递归
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. Array.prototype.deepFlat = function () {
  5. var arr = this,
  6. res = [];
  7. (function _(arr) {
  8. arr.forEach(function (item) {
  9. if (Array.isArray(item)) {
  10. _(item);
  11. } else {
  12. res.push(item);
  13. }
  14. })
  15. })(arr);
  16. return res;
  17. }
  18. console.log(arr.deepFlat(Infinity));
  19. // // // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. //方法六
  2. //生成器函数
  3. const arr = [0, [1, 2, [3, 4, [5, 6, [7, 8, [9]]]]]];
  4. function* deepFlat(arr) {
  5. for (var item of arr) {
  6. if (Array.isArray(item)) {
  7. yield* deepFlat(item);
  8. } else {
  9. yield item;
  10. }
  11. }
  12. }
  13. //平铺执行结果
  14. console.log([...deepFlat(arr)]);
  15. // // // // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.prototype.flatMap()

ECMAScript 2020

首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。

  1. //flat + map === flatMap
  2. const arr = ['123', '456', '789'];
  3. // 希望的格式:['1','2','3','4','5',...];
  4. //返回数组为二维数组
  5. const newArr = arr.map(function (item) {
  6. // console.log(item); //123 456 789
  7. // console.log(item.split(''));
  8. //["1", "2", "3"] ["4", "5", "6"] ["7", "8", "9"]
  9. return item.split('');
  10. });
  11. console.log(newArr);
  12. //[Array(3), Array(3), Array(3)]
  13. //变为一维数组
  14. const newArr2 = arr.map(function (item) {
  15. // console.log(item); //123 456 789
  16. // console.log(item.split(''));
  17. //["1", "2", "3"] ["4", "5", "6"] ["7", "8", "9"]
  18. return item.split('');
  19. }).flat();
  20. console.log(newArr2);
  21. //["1", "2", "3", "4", "5", "6", "7", "8", "9"]
  1. // flatMap()
  2. //遍历 + 扁平化
  3. //map + flat
  4. //效率更高,一体化完成
  5. //ECMA - 262 / MDN
  6. const newArr = arr.flatMap(function (item) {
  7. // console.log(item); //123 456 789
  8. // console.log(item.split(''));
  9. //["1", "2", "3"] ["4", "5", "6"] ["7", "8", "9"]
  10. return item.split('');
  11. })
  12. console.log(newArr);
  13. //["1", "2", "3", "4", "5", "6", "7", "8", "9"]
  1. //返回值为新的数组
  2. console.log(newArr === arr); //false
  1. /**
  2. * flatMap(function(item, index, arr){})
  3. * @arguments[0] 参数一为回调函数
  4. * @arguments[1] 参数二可以更改回调内this指向
  5. * @item 当前遍历的元素
  6. * @index 当前遍历的元素在数组中对应的下标
  7. * @arr 数组本身
  8. * @this 默认指向window 严格模式为undefined
  9. */
  10. const newArr = arr.flatMap(function (item, index, arr) {
  11. console.log(this);
  12. }, {
  13. a: 1
  14. })
  1. const arr = ['My name\'s kevin', 'I am 30', 'years old.'];
  2. const newArr = arr.map(function (item) {
  3. return item.split(' ');
  4. })
  5. console.log(newArr);
  6. /**
  7. * (3) [Array(3), Array(3), Array(2)]
  8. * 0: (3) ["My", "name's", "kevin"]
  9. * 1: (3) ["I", "am", "30"]
  10. * 2: (2) ["years", "old."]
  11. * length: 3
  12. * __proto__: Array(0)
  13. */
  14. const newArr2 = arr.flatMap(function (item) {
  15. return item.split(' ');
  16. })
  17. console.log(newArr2);
  18. //["My", "name's", "kevin", "I", "am", "30", "years", "old."]
  1. //希望只要遇到负数就会跟前一位相加,并且把运算的过程的字符串打印出来
  2. const arr = [1, -2, -3, 5, 8, -9, 6, 7, 0];
  3. const newArr = arr.flatMap(function (item, index) {
  4. if (item < 0 && index >= 1) {
  5. return [item, `${item}+${arr[index - 1]}=${item + arr[index - 1]}`];
  6. }
  7. return item;
  8. })
  9. console.log(newArr);
  10. //[1, -2, "-2+1=-1", -3, "-3+-2=-5", 5, 8, -9, "-9+8=-1", 6, 7, 0]

写一个myFlatMap()方法

  1. const arr = ['123', '456', '789'];
  2. Array.prototype.myFlagMap = function (cb) {
  3. if (typeof cb !== 'function') {
  4. throw new TypeError('Callback must be a function');
  5. }
  6. var arr = this,
  7. //有可能有第二个参数
  8. arg2 = arguments[1],
  9. res = [],
  10. item;
  11. for (var i = 0; i < arr.length; i++) {
  12. item = cb.apply(arg2, [arr[i], i, arr]);
  13. item && res.push(item);
  14. }
  15. return res.flat();
  16. }
  17. const newArr = arr.myFlagMap(function (item) {
  18. return item.split('');
  19. })
  20. console.log(newArr);
  21. //["1", "2", "3", "4", "5", "6", "7", "8", "9"]

Array.prototype.reduce()

归纳函数,数据筛选和归纳,划分,代码更易于维护和更新。

对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

  1. const array1 = [1, 2, 3, 4];
  2. const reducer = (accumulator, currentValue) => accumulator + currentValue;
  3. // 1 + 2 + 3 + 4
  4. console.log(array1.reduce(reducer));
  5. // expected output: 10
  6. // 5 + 1 + 2 + 3 + 4
  7. console.log(array1.reduce(reducer, 5));
  8. // expected output: 15

reducer 函数接收4个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)

您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。

语法

  1. arr.reduce(callback(accumulator, currentValue, index, array), initialValue);

参数

  • callback:执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数

    • accumulator:累计器累计回调的返回值; 它是上一次调用回调时返回的累积值
    • currentValue:数组中正在处理的元素
    • index:可选,数组中正在处理的当前元素的索引(如果提供了initialValue,则起始索引号为0否则从索引1起始)
    • arrar:可选,调用reduce()的数组
  • initialValue:可选,作为第一次调用 callback函数时的第一个参数的值。

    • 如果没有提供初始值,则将使用数组中的第一个元素。
    • 在没有初始值的空数组上调用 reduce 将报错。

返回值

函数累计处理的结果

描述

reduce为数组中的每一个元素依次执行callback函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:

  • accumulator 累计器
  • currentValue 当前值
  • currentIndex 当前索引
  • array 数组

回调函数第一次执行时,accumulatorcurrentValue的取值有两种情况:

  • 如果调用reduce()时提供了initialValueaccumulator取值为initialValuecurrentValue取数组中的第一个值;
  • 如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
  • 如果数组为空且没有提供initialValue,会抛出TypeError
  • 如果数组仅有一个元素(无论位置如何)并且没有提供initialValue, 或者有提供initialValue但是数组为空,那么此唯一值将被返回并且callback不会被执行。

reduce() 如何运行

  1. [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  2. return accumulator + currentValue;
  3. });
  4. //由`reduce`返回的值将是最后一次回调返回值(10)。

callback 被调用四次,每次调用的参数和返回值如下表:

callback accumulator currentValue currentIndex array return value
first call 0 1 1 [0, 1, 2, 3, 4] 1
second call 1 2 2 [0, 1, 2, 3, 4] 3
third call 3 3 3 [0, 1, 2, 3, 4] 6
fourth call 6 4 4 [0, 1, 2, 3, 4] 10

使用箭头函数来代替完整的函数。 下面的代码将产生与上面的代码相同的输出:

  1. [0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );

提供一个初始值作为reduce()方法的第二个参数,以下是运行过程及结果:

  1. [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
  2. return accumulator + currentValue
  3. }, 10)
  4. //这种情况下reduce()返回的值是20。
callback accumulator currentValue currentIndex array return value
first call 10 0 0 [0, 1, 2, 3, 4] 10
second call 10 1 1 [0, 1, 2, 3, 4] 11
third call 11 2 2 [0, 1, 2, 3, 4] 13
fourth call 13 3 3 [0, 1, 2, 3, 4] 16
fifth call 16 4 4 [0, 1, 2, 3, 4] 20

示例

数组里所有值的和

  1. var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  2. return accumulator + currentValue;
  3. }, 0);
  4. // 和为 6
  5. //箭头函数的形式
  6. var total = [ 0, 1, 2, 3 ].reduce(
  7. ( acc, cur ) => acc + cur,
  8. 0
  9. );

累加对象数组里的值

  1. //要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数。
  2. var initialValue = 0;
  3. var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
  4. return accumulator + currentValue.x;
  5. },initialValue)
  6. console.log(sum) // logs 6
  7. //箭头函数形式
  8. var initialValue = 0;
  9. var sum = [{x: 1}, {x:2}, {x:3}].reduce(
  10. (accumulator, currentValue) => accumulator + currentValue.x
  11. ,initialValue
  12. );
  13. console.log(sum) // logs 6

将二维数组转化为一维

  1. var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  2. function(a, b) {
  3. return a.concat(b);
  4. },
  5. []
  6. );
  7. // flattened is [0, 1, 2, 3, 4, 5]
  8. //箭头函数形式
  9. var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  10. ( acc, cur ) => acc.concat(cur),
  11. []
  12. );

计算数组中每个元素出现的次数

  1. var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
  2. var countedNames = names.reduce(function (allNames, name) {
  3. if (name in allNames) {
  4. allNames[name]++;
  5. }
  6. else {
  7. allNames[name] = 1;
  8. }
  9. return allNames;
  10. }, {});
  11. // countedNames is:
  12. // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

按属性对object分类

  1. var people = [
  2. { name: 'Alice', age: 21 },
  3. { name: 'Max', age: 20 },
  4. { name: 'Jane', age: 20 }
  5. ];
  6. function groupBy(objectArray, property) {
  7. return objectArray.reduce(function (acc, obj) {
  8. var key = obj[property];
  9. if (!acc[key]) {
  10. acc[key] = [];
  11. }
  12. acc[key].push(obj);
  13. return acc;
  14. }, {});
  15. }
  16. var groupedPeople = groupBy(people, 'age');
  17. // groupedPeople is:
  18. // {
  19. // 20: [
  20. // { name: 'Max', age: 20 },
  21. // { name: 'Jane', age: 20 }
  22. // ],
  23. // 21: [{ name: 'Alice', age: 21 }]
  24. // }

使用扩展运算符和initialValue绑定包含在对象数组中的数组

  1. // friends - 对象数组
  2. // where object field "books" - list of favorite books
  3. var friends = [{
  4. name: 'Anna',
  5. books: ['Bible', 'Harry Potter'],
  6. age: 21
  7. }, {
  8. name: 'Bob',
  9. books: ['War and peace', 'Romeo and Juliet'],
  10. age: 26
  11. }, {
  12. name: 'Alice',
  13. books: ['The Lord of the Rings', 'The Shining'],
  14. age: 18
  15. }];
  16. // allbooks - list which will contain all friends' books +
  17. // additional list contained in initialValue
  18. var allbooks = friends.reduce(function(prev, curr) {
  19. return [...prev, ...curr.books];
  20. }, ['Alphabet']);
  21. // allbooks = [
  22. // 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
  23. // 'Romeo and Juliet', 'The Lord of the Rings',
  24. // 'The Shining'
  25. // ]

数组去重

  1. let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
  2. let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  3. if (accumulator.indexOf(currentValue) === -1) {
  4. accumulator.push(currentValue)
  5. }
  6. return accumulator
  7. }, [])
  8. console.log(myOrderedArray)
  1. let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
  2. let result = arr.sort().reduce((init, current) => {
  3. if(init.length === 0 || init[init.length-1] !== current) {
  4. init.push(current);
  5. }
  6. return init;
  7. }, []);
  8. console.log(result); //[1,2,3,4,5]

扁平化数组里面对象结构

  1. //利用reduce扁平化数组里面对象结构
  2. var data = [{
  3. value: "1,2"
  4. }, {
  5. value: "3"
  6. }, {
  7. value: "4,5"
  8. }];
  9. var res = data.reduce(function (prev, elem) {
  10. //数据操作
  11. // console.log(elem.value); //1,2 3 4,5
  12. //数组每一项的值进行split字符串以逗号方式拆分
  13. //并让空数组prev用concat方法拼接在一起
  14. return prev.concat(elem.value.split(','));
  15. }, []);
  16. console.log(res);
  17. //["1", "2", "3", "4", "5"]

分析reduce

  1. /**
  2. * 分析reduce()
  3. * 结论1:第一次return prev参数(初始值为空数组(initialValue参数提供)),
  4. * 结论2:每一次遍历data数据,都可以对prev数组进行数据操作
  5. * 结论3:归纳函数是在条件范围之内往容器里扔东西且让容器成为一个新的东西
  6. */
  7. var initialValue = [];
  8. courseData.reduce(function (prev, elem, index, arr) {
  9. //情况1:prev值打印一次 后面打印为undefined
  10. // console.log(prev);
  11. // console.log(arr);
  12. //情况2:证明prev与initialValue是否同一个东西 结果是true
  13. // console.log(prev === initialValue);
  14. //true X 1 / false X 6(因为后面为undefined)
  15. //情况3:证明reduce每次遍历时回调函数里必须return prev
  16. //侧面说明reduce程序靠返回prev才能继续执行下去
  17. //每次return prev; prev里才有值
  18. // console.log(prev); //打印7个[]
  19. // return prev;
  20. }, initialValue);

案例1

  1. //应用1:把courseData里的某一字段(course)数据归纳到一个数组中
  2. //说明每次数据进行reduce的时候可以操作prev,然后把操作后的prev return 出去
  3. //1.遍历数据
  4. var nArr = courseData.reduce(function (prev, elem, index, arr) {
  5. //2.操作prev
  6. prev.push(elem.course);
  7. //3.return prev出去
  8. return prev;
  9. }, initialValue);
  10. console.log(nArr);
  11. //["前端开发之企业级深度JavaScript特训课【JS++前端】", "WEB前端工程师就业班之深度JS DOM+讲师辅导-第3期【JS++前端】", "前端开发之企业级深度HTML特训课【JS++前端】", "前端开发之企业级深度CSS特训课【JS++前端】", "前端就业班VueJS+去哪儿网+源码课+讲师辅导-第3期【JS++前端】", "前端就业班ReactJS+新闻头条实战+讲师辅导-第3期【JS++前端】", "WEB前端开发工程师就业班-直播/录播+就业辅导-第3期【JS++前端】"]

案例2

  1. //应用2:把免费课程都筛选到一个数组中
  2. //跟filter区别:filter为过滤方式,reduce为归纳的方式
  3. //过滤的方式是返回布尔值true就放,false就扔掉
  4. //归纳是在条件范围之内往容器里扔东西且让容器成为一个新的东西
  5. var nArr1 = courseData.reduce(function (prev, elem, index, arr) {
  6. if (elem.is_free === '1') {
  7. prev.push(elem);
  8. }
  9. return prev;
  10. }, initialValue);
  11. console.log(nArr1);
  12. /**
  13. * console.log(nArr1):
  14. * (3) [{…}, {…}, {…}]
  15. * 0: {id: "1", course: "前端开发之企业级深度JavaScript特训课【JS++前端】", classes: "19", teacher: "小野", img: "ecmascript.jpg", …}
  16. * 1: {id: "3", course: "前端开发之企业级深度HTML特训课【JS++前端】", classes: "3", teacher: "小野", img: "html.jpg", …}
  17. * 2: {id: "4", course: "前端开发之企业级深度CSS特训课【JS++前端】", classes: "5", teacher: "小野", img: "css.jpg", …}
  18. * length: 3
  19. */

案例3

  1. //应用3
  2. //把cookies信息整理为对象格式的数据
  3. //期待格式
  4. // {
  5. // BAIDUID: '04B95FD81DCE5E4D8FE723A4F46FC20A',
  6. // PSTM: '1603714330',
  7. // ...
  8. // }
  9. //cookies数据
  10. var cookieDatas = 'BIDUPSID=04B95FD81DCE5E4D68904041B9D32D3B; PSTM=1603714330; BAIDUID=04B95FD81DCE5E4D8FE723A4F46FC20A:FG=1; PANWEB=1; BDUSS=m9jaG5zdEw5c2Fuay1MOWtHQUV-RlNjZFpyeFJQM3lDSkFuMkdROXVVOE9WNzVmRVFBQUFBJCQAAAAAAAAAAAEAAAAX6jgcMjczMTIyMTg4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7Kll8OypZfN; BDUSS_BFESS=m9jaG5zdEw5c2Fuay1MOWtHQUV-RlNjZFpyeFJQM3lDSkFuMkdROXVVOE9WNzVmRVFBQUFBJCQAAAAAAAAAAAEAAAAX6jgcMjczMTIyMTg4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7Kll8OypZfN; MCITY=-138:'
  11. //以 ; 分割数组元素
  12. var cookiesArr = cookieDatas.split(';')
  13. // console.log(cookiesArr);
  14. //["BIDUPSID=04B95FD81DCE5E4D68904041B9D32D3B", " PSTM=1603714330", " BAIDUID=04B95FD81DCE5E4D8FE723A4F46FC20A:FG=1", " PANWEB=1",...]
  15. //使用reduce归纳 以 = 整理的数组
  16. var cookieObj = cookiesArr.reduce(function (prev, elem, index, arr){
  17. // = 号 分割每一项数组元素里的数据
  18. var item = elem.split('=');
  19. // console.log(item);
  20. //["BIDUPSID", "04B95FD81DCE5E4D68904041B9D32D3B"] ...
  21. //这里prev是初始值{}
  22. prev[item[0]] = item[1];
  23. return prev;
  24. }, {});
  25. console.log(cookieObj);
  26. /**
  27. * console.log(cookieObj);:
  28. * {
  29. * BIDUPSID: "04B95FD81DCE5E4D68904041B9D32D3B",
  30. * " PSTM": "1603714330", " BAIDUID": "04B95FD81DCE5E4D8FE723A4F46FC20A:FG",
  31. * " PANWEB": "1",
  32. * "BDUSS":"m9jaG5zdEw5c2Fuay1MOWtHQUV-RlNjZFpyeFJQM3lDSkFuMkd…AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7Kll8OypZfN",
  33. * …
  34. * }
  35. */

重写

  1. /**
  2. * 重写reduce()
  3. * 归纳函数,对数据进行筛选,归纳
  4. * 默认改变不了this的指向,但自己写的话新增改变this指向(参数3)
  5. *
  6. * 基本形态:
  7. * [].reduce(function(elem,index,arr){});
  8. *
  9. * 改造形态:
  10. * [].reduce(function(prev,elem,index,arr){},initialValue);
  11. *
  12. * 进行数据过滤
  13. * @返回值 不return 为 undefined
  14. * @返回值 返回操作后(归纳,筛选)得到的数组
  15. *
  16. * @参数1: 回调函数
  17. * @参数2: initialValue(必填)
  18. * @回调函数参数1: 操作后返回的数组(第一次默认为[],如有initialValue,用initialValue)
  19. * @回调函数参数2: 元素
  20. * @回调函数参数3: 索引(可选)
  21. * @回调函数参数4: 数组本身(可选)
  22. *
  23. * 要求:
  24. * 1.必须数组调用
  25. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  26. * 3.兼容IE和es3
  27. */
  28. //封装myReduce
  29. Array.prototype.myReduce = function (fn, initialValue) {
  30. var arr = this,
  31. //兼容es3只能for循环
  32. len = arr.length,
  33. //第二参数可传可不传利用arguments[1]
  34. //传了指向arguments[2], 没传指向window
  35. arg2 = arguments[2] || window;
  36. for (var i = 0; i < len; i++) {
  37. item = deepClone(arr[i]);
  38. //每遍历一次数组,执行一次回调函数fn
  39. //每一次调用fn的返回值就是initialValue
  40. initialValue = fn.apply(arg2, [initialValue, arr[i], i, arr]);
  41. //因为第三参数需要改变this指向所以改写为fn.apply(this,[initialValue,参数2,参数3,参数4])
  42. }
  43. //这里记得return initialValue 否则程序无法正常执行且报错
  44. return initialValue;
  45. }
  46. //使用myReduce
  47. //cookies数据
  48. var cookieDatas = 'BIDUPSID=04B95FD81DCE5E4D68904041B9D32D3B; PSTM=1603714330; BAIDUID=04B95FD81DCE5E4D8FE723A4F46FC20A:FG=1; PANWEB=1; BDUSS=m9jaG5zdEw5c2Fuay1MOWtHQUV-RlNjZFpyeFJQM3lDSkFuMkdROXVVOE9WNzVmRVFBQUFBJCQAAAAAAAAAAAEAAAAX6jgcMjczMTIyMTg4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7Kll8OypZfN; BDUSS_BFESS=m9jaG5zdEw5c2Fuay1MOWtHQUV-RlNjZFpyeFJQM3lDSkFuMkdROXVVOE9WNzVmRVFBQUFBJCQAAAAAAAAAAAEAAAAX6jgcMjczMTIyMTg4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7Kll8OypZfN; MCITY=-138:'
  49. //以 ; 分割数组元素
  50. var cookiesArr = cookieDatas.split(';');
  51. // //使用reduce归纳 以 = 整理的数组
  52. var cookieObj = cookiesArr.myReduce(function (prev, elem) {
  53. // = 号 分割每一项数组元素里的数据
  54. var item = elem.split('=');
  55. // console.log(item);
  56. //["BIDUPSID", "04B95FD81DCE5E4D68904041B9D32D3B"] ...
  57. //这里prev是初始值{}
  58. //键名=键值
  59. prev[item[0]] = item[1];
  60. return prev;
  61. }, {});
  62. console.log(cookieObj);

Array.prototype.reduceRight()

重写

  1. /**
  2. * 重写reduceRight()
  3. * 跟reduce,差不多,就是顺序为降序
  4. * 归纳函数,对数据进行筛选,归纳
  5. * 默认改变不了this的指向,但自己写的话新增改变this指向(参数3)
  6. *
  7. * 基本形态:
  8. * [].reduceRight(function(elem,index,arr){});
  9. *
  10. * 改造形态:
  11. * [].reduceRight(function(prev,elem,index,arr){},initialValue);
  12. *
  13. * 进行数据过滤
  14. * @返回值 不return 为 undefined
  15. * @返回值 返回操作后(归纳,筛选)得到的数组
  16. *
  17. * @参数1: 回调函数
  18. * @参数2: initialValue(必填)
  19. * @回调函数参数1: 操作后返回的数组(第一次默认为[],如有initialValue,用initialValue)
  20. * @回调函数参数2: 元素
  21. * @回调函数参数3: 索引(可选)
  22. * @回调函数参数4: 数组本身(可选)
  23. *
  24. * 要求:
  25. * 1.必须数组调用
  26. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  27. * 3.兼容IE和es3
  28. */
  29. //封装myReduceRight
  30. Array.prototype.myReduceRight = function (fn, initialValue) {
  31. var arr = this,
  32. //兼容es3只能for循环
  33. len = arr.length,
  34. //第二参数可传可不传利用arguments[1]
  35. //传了指向arguments[2], 没传指向window
  36. arg2 = arguments[2] || window;
  37. for (var i = len - 1; i >= 0; i--) {
  38. item = deepClone(arr[i]);
  39. //每遍历一次数组,执行一次回调函数fn
  40. //每一次调用fn的返回值就是initialValue
  41. initialValue = fn.apply(arg2, [initialValue, arr[i], i, arr]);
  42. //因为第三参数需要改变this指向所以改写为fn.apply(this,[initialValue,参数2,参数3,参数4])
  43. }
  44. //这里记得return initialValue 否则程序无法正常执行且报错
  45. return initialValue;
  46. }

Array.prototype.map()

创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。

  1. const array1 = [1, 4, 9, 16];
  2. // pass a function to map
  3. const map1 = array1.map((x) => x * 2);
  4. console.log(map1);
  5. // expected output: Array [2, 8, 18, 32]

语法

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

参数

  • callback:生成新数组元素的函数

    • currentValue:数组中正在处理的当前元素
    • index:可选,当前元素的索引
    • array:可选,当前的数组
  • thisArg:执行 callback 函数时值被用作this

返回值

一个由原数组每个元素执行回调函数的结果组成的新数组。

描述

  • map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数
  • callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组。
  • callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。
  • 如果 thisArg 参数提供给map,则会被用作回调函数的this值。否则undefined会被用作回调函数的this
  • map不修改调用它的原数组本身
  • map 方法处理数组元素的范围是在 callback 方法第一次调用之前就已经确定了。调用map方法之后追加的数组元素不会被callback访问。
  • 如果存在的数组元素改变了,那么传给callback的值是map访问该元素时的值。在map函数调用后但在访问该元素前,该元素被删除的话,则无法被访问到。

示例

求数组中每个元素的平方根

  1. //创建了一个新数组,值为原数组中对应数字的平方根。
  2. var numbers = [1, 4, 9];
  3. var roots = numbers.map(Math.sqrt);
  4. // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]

使用 map 重新格式化数组中的对象

  1. //使用一个包含对象的数组来重新创建一个格式化后的数组。
  2. var kvArray = [{key: 1, value: 10},
  3. {key: 2, value: 20},
  4. {key: 3, value: 30}];
  5. var reformattedArray = kvArray.map(function(obj) {
  6. var rObj = {};
  7. rObj[obj.key] = obj.value;
  8. return rObj;
  9. });
  10. // reformattedArray 数组为: [{1: 10}, {2: 20}, {3: 30}],
  11. // kvArray 数组未被修改:
  12. // [{key: 1, value: 10},
  13. // {key: 2, value: 20},
  14. // {key: 3, value: 30}]

使用一个包含一个参数的函数来mapping(构建)一个数字数组

  1. //当函数需要一个参数时map的工作方式。
  2. //当map循环遍历原始数组时,这个参数会自动被分配成数组中对应的每个元素。
  3. var numbers = [1, 4, 9];
  4. var doubles = numbers.map(function(num) {
  5. return num * 2;
  6. });
  7. // doubles数组的值为: [2, 8, 18]
  8. // numbers数组未被修改: [1, 4, 9]

一般的map 方法

  1. //在一个 String 上使用 map 方法获取字符串中每个字符所对应的 ASCII 码组成的数组
  2. var map = Array.prototype.map
  3. var a = map.call("Hello World", function(x) {
  4. return x.charCodeAt(0);
  5. })
  6. // a的值为[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

querySelectorAll应用

  1. //如何去遍历用 querySelectorAll 得到的动态对象集合。在这里获得了文档里所有选中的选项,并将其打印:
  2. var elems = document.querySelectorAll('select option:checked');
  3. var values = Array.prototype.map.call(elems, function(obj) {
  4. return obj.value;
  5. });

重写

  1. //map映射
  2. /**
  3. * 重写map()
  4. *
  5. * @返回值 返回一个新的数组
  6. * @返回值 可以返回参数为元素的元素本身(可不设定条件)
  7. * @返回值 可以返回任意加工过的元素数组集合,会改变原数组
  8. *
  9. * @参数1: 回调函数
  10. * @参数2: 可更改this指向,默认为window(可选)
  11. * @回调函数参数1: 元素
  12. * @回调函数参数2: 索引(可选)
  13. * @回调函数参数3: 数组本身(可选)
  14. *
  15. * 要求:
  16. * 1.必须数组调用
  17. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  18. * 3.兼容IE和es3
  19. */
  20. //封装myMap
  21. Array.prototype.myMap = function (fn) {
  22. var arr = this,
  23. //兼容es3只能for循环
  24. len = arr.length,
  25. //第二参数可传可不传利用arguments[1]
  26. //传了指向arg2, 没传指向window
  27. arg2 = arguments[1] || window,
  28. //新数组容器
  29. _newArr = [],
  30. item;
  31. for (var i = 0; i < len; i++) {
  32. //克隆对象
  33. item = deepClone(arr[i]);
  34. _newArr.push(fn.apply(arg2, [item, i, arr]));
  35. }
  36. return _newArr;
  37. };
  38. //参数1:回调函数fn
  39. //该函数直接返回修改过元素集合的数组
  40. var fn = function (elem, index, array) {
  41. //这里编辑返回加工后的结果
  42. //会改变原有数据
  43. elem.course = this.name + elem.course;
  44. //return undefined/null 不会修改数组元素
  45. return elem;
  46. };
  47. //使用myMap
  48. var newArr = courseData.myMap(fn, {
  49. name: "test:",
  50. });
  51. console.log(newArr);

Array.prototype.filter()

创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

  1. const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
  2. const result = words.filter(word => word.length > 6);
  3. console.log(result);
  4. // expected output: Array ["exuberant", "destruction", "present"]

语法

  1. var newArray = arr.filter(callback(element, index, array), thisArg);

参数

  • callback:用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保

    • element:数组中当前正在处理的元素。
    • index:正在处理的元素在数组中的索引。
    • array:被遍历的数组本身
  • thisArg:执行 callback 时,用于 this 的值。

返回值

一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。

描述

filter 不会改变原数组,它返回过滤后的新数组。

filter 遍历的元素范围在第一次调用 callback 之前就已经确定了。

在调用 filter 之后被添加到数组中的元素不会被 filter 遍历到。

如果已经存在的元素被改变了,则他们传入 callback 的值是 filter 遍历到它们那一刻的值。被删除或从来未被赋值的元素不会被遍历到。

示例

筛选排除所有较小的值

创建了一个新数组,该数组的元素由原数组中值大于 10 的元素组成。

  1. function isBigEnough(element) {
  2. return element >= 10;
  3. }
  4. var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
  5. // filtered is [12, 130, 44]

过滤 JSON 中的无效条目

以下示例使用 filter() 创建具有非零 id 的元素的 json。

  1. //filter 为数组中的每个元素调用一次 callback 函数,并利用所有使得 callback 返回 true 或等价于 true 的值的元素创建一个新数组。
  2. var arr = [
  3. { id: 15 },
  4. { id: -1 },
  5. { id: 0 },
  6. { id: 3 },
  7. { id: 12.2 },
  8. { },
  9. { id: null },
  10. { id: NaN },
  11. { id: 'undefined' }
  12. ];
  13. var invalidEntries = 0;
  14. function isNumber(obj) {
  15. return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
  16. }
  17. function filterByID(item) {
  18. if (isNumber(item.id) && item.id !== 0) {
  19. return true;
  20. }
  21. invalidEntries++;
  22. return false;
  23. }
  24. var arrByID = arr.filter(filterByID);
  25. console.log('Filtered Array\n', arrByID);
  26. // Filtered Array
  27. // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
  28. console.log('Number of Invalid Entries = ', invalidEntries);
  29. // Number of Invalid Entries = 5

在数组中搜索

下例使用 filter() 根据搜索条件来过滤数组内容。

  1. var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
  2. function filterItems(query) {
  3. return fruits.filter(function(el) {
  4. return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
  5. })
  6. }
  7. /**
  8. * console.log('apple'.indexOf('ap')); //0
  9. * console.log('apple'.indexOf('an')); //-1
  10. * console.log('banana'.indexOf('an')); //1
  11. * console.log('orange'.indexOf('an')); //2
  12. */
  13. console.log(filterItems('ap')); // ['apple', 'grapes']
  14. console.log(filterItems('an')); // ['banana', 'mango', 'orange']

重写

  1. /**
  2. * 重写filter()
  3. * 进行数据过滤
  4. * @返回值 true返回一个新的数组(不影响原来的数组)
  5. * @返回值 false返回一个空的数组
  6. * @返回值 条件符合 -> true -> 返回符合条件内容
  7. *
  8. * @参数1: 回调函数
  9. * @参数2: 可更改this指向,默认为window(可选)
  10. * @回调函数参数1: 元素
  11. * @回调函数参数2: 索引(可选)
  12. * @回调函数参数3: 数组本身(可选)
  13. *
  14. * 要求:
  15. * 1.必须数组调用
  16. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  17. * 3.兼容IE和es3
  18. */
  19. //封装myFilter
  20. Array.prototype.myFilter = function (fn) {
  21. var arr = this,
  22. //兼容es3只能for循环
  23. len = arr.length,
  24. //第二参数可传可不传利用arguments[1]
  25. //传了指向arg2, 没传指向window
  26. arg2 = arguments[1] || window,
  27. //新数组容器
  28. _newArr = [],
  29. item;
  30. for (var i = 0; i < len; i++) {
  31. //每遍历一次数组,执行一次回调函数fn
  32. // fn(arr[i], i, arr);
  33. //因为第二参数需要改变this指向所以改写为fn.apply(参数1,[参数1,参数2])
  34. //为真: push到新数组
  35. //为假: 不做任何操作
  36. //注意: push(arr[i])里面还是持有原来数据的引用,修改会影响原有数据
  37. //解决方法: 需要深拷贝
  38. item = deepClone(arr[i]);
  39. fn.apply(arg2, [arr[i], i, arr]) ? _newArr.push(item) : '';
  40. }
  41. return _newArr;
  42. }
  43. //使用myFilter
  44. var newArr = courseData.myFilter(function (elem, index, array) {
  45. //这里返回true且符合条件的数据 / false
  46. return elem.is_free === '0';
  47. }, {
  48. name: 'test'
  49. })
  50. console.log(newArr);

备注:这里是深拷贝的封装代码

  1. //循环对象之前需要检测对象里面的属性值是否是引用值
  2. //当发现有引用值的时候需要遍历
  3. //不仅判断键值对是否含有引用值,还得判断是对象还是数组
  4. //利用递归克隆函数进行再次循环
  5. function deepClone(origin, target) {
  6. //万一用户不传target参数,自己默认创建空对象
  7. var target = target || {},
  8. toStr = Object.prototype.toString,
  9. arrType = '[object Array]';
  10. for (var key in origin) {
  11. //排除原型上的属性
  12. if (origin.hasOwnProperty(key)) {
  13. //判断是否为引用值 同时排除null
  14. if (typeof (origin[key]) === 'object' && origin[key] !== null) {
  15. //判断引用值是否为数组类型
  16. if (toStr.call(origin[key]) === arrType) {
  17. //创建空数组
  18. target[key] = [];
  19. } else {
  20. //引用值是对象
  21. //创建空对象
  22. target[key] = {};
  23. }
  24. //递归,再次遍历
  25. deepClone(origin[key], target[key]);
  26. } else {
  27. //这里是递归的出口
  28. //遍历第一层 浅拷贝
  29. target[key] = origin[key];
  30. }
  31. }
  32. }
  33. return target;
  34. }

Array.prototype.forEach()

对数组的每个元素执行一次给定的函数。总是返回 undefined 值,并且不可链式调用。

注意: 除了抛出异常以外,没有办法中止或跳出 forEach() 循环。

  1. const array1 = ['a', 'b', 'c'];
  2. array1.forEach(element => console.log(element));
  3. // expected output: "a"
  4. // expected output: "b"
  5. // expected output: "c"

语法

  1. arr.forEach(callback(currentValue, index, array), thisArg)

参数

  • callback:为数组中每个元素执行的函数

    • currentValue:数组中正在处理的当前元素
    • index:可选,数组中正在处理的当前元素索引
    • array:可选,正在操作的数组
  • thisArg:可选,当执行回调函数 callback 时,用作 this 的值

返回值

undefined

示例

不对未初始化的值进行任何操作(稀疏数组)

  1. const arraySparse = [1, 3, , 7];
  2. let numCallbackRuns = 0;
  3. arraySparse.forEach(function (element) {
  4. console.log(element);
  5. numCallbackRuns++;
  6. });
  7. console.log("numCallbackRuns: ", numCallbackRuns);
  8. // 1
  9. // 3
  10. // 7
  11. // numCallbackRuns: 3

将 for 循环转换为 forEach

  1. const items = ['item1', 'item2', 'item3'];
  2. const copy = [];
  3. // before
  4. for (let i = 0; i < items.length; i++) {
  5. copy.push(items[i]);
  6. }
  7. // after
  8. items.forEach(function (item) {
  9. copy.push(item);
  10. });
  1. //打印出数组的内容
  2. function logArrayElements(element, index, array) {
  3. console.log(`a[${index}]=` + element);
  4. }
  5. // 注意索引 2 被跳过了,因为在数组的这个位置没有项
  6. [2, 5, , 9].forEach(logArrayElements);
  7. // logs:
  8. // a[0] = 2
  9. // a[1] = 5
  10. // a[3] = 9

素材:data数据

  1. var courseData = [{
  2. "id": "1",
  3. "course": "前端开发之企业级深度JavaScript特训课【JS++前端】",
  4. "classes": "19",
  5. "teacher": "小野",
  6. "img": "ecmascript.jpg",
  7. "is_free": "1",
  8. "datetime": "1540454477",
  9. "price": "0"
  10. },
  11. {
  12. "id": "2",
  13. "course": "WEB前端工程师就业班之深度JS DOM+讲师辅导-第3期【JS++前端】",
  14. "classes": "22",
  15. "teacher": "小野",
  16. "img": "dom.jpg",
  17. "is_free": "0",
  18. "datetime": "1540454477",
  19. "price": "699"
  20. },
  21. {
  22. "id": "3",
  23. "course": "前端开发之企业级深度HTML特训课【JS++前端】",
  24. "classes": "3",
  25. "teacher": "小野",
  26. "img": "html.jpg",
  27. "is_free": "1",
  28. "datetime": "1540454477",
  29. "price": "0"
  30. },
  31. {
  32. "id": "4",
  33. "course": "前端开发之企业级深度CSS特训课【JS++前端】",
  34. "classes": "5",
  35. "teacher": "小野",
  36. "img": "css.jpg",
  37. "is_free": "1",
  38. "datetime": "1540454477",
  39. "price": "0"
  40. },
  41. {
  42. "id": "5",
  43. "course": "前端就业班VueJS+去哪儿网+源码课+讲师辅导-第3期【JS++前端】",
  44. "classes": "50",
  45. "teacher": "哈默",
  46. "img": "vuejs.jpg",
  47. "is_free": "0",
  48. "datetime": "1540454477",
  49. "price": "1280"
  50. },
  51. {
  52. "id": "6",
  53. "course": "前端就业班ReactJS+新闻头条实战+讲师辅导-第3期【JS++前端】",
  54. "classes": "21",
  55. "teacher": "托尼",
  56. "img": "reactjs.jpg",
  57. "is_free": "0",
  58. "datetime": "1540454477",
  59. "price": "2180"
  60. },
  61. {
  62. "id": "7",
  63. "course": "WEB前端开发工程师就业班-直播/录播+就业辅导-第3期【JS++前端】",
  64. "classes": "700",
  65. "teacher": "JS++名师团",
  66. "img": "jiuyeban.jpg",
  67. "is_free": "0",
  68. "datetime": "1540454477",
  69. "price": "4980"
  70. }
  71. ]

重写

  1. /**
  2. * 重写forEach()
  3. * @参数1: 回调函数
  4. * @参数2: 可更改this指向,默认为window(可选)
  5. * @回调函数参数1: 元素
  6. * @回调函数参数2: 索引(可选)
  7. * @回调函数参数3: 数组本身(可选)
  8. *
  9. * 1.必须数组调用
  10. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  11. * 3.兼容IE和es3
  12. */
  13. Array.prototype.myForEach = function (fn) {
  14. var arr = this,
  15. //兼容es3只能for循环
  16. len = arr.length,
  17. //第二参数可传可不传利用arguments[1]
  18. //传了指向arg2, 没传指向window
  19. arg2 = arguments[1] || window;
  20. for (var i = 0; i < len; i++) {
  21. //每遍历一次数组,执行一次回调函数fn
  22. // fn(arr[i], i, arr);
  23. //因为第二参数需要改变this指向所以改写为fn.apply(参数1,[参数1,参数2])
  24. fn.apply(arg2, [arr[i], i, arr]);
  25. }
  26. }
  27. //使用myForEach
  28. courseData.myForEach(function (elem, index, array) {
  29. console.log(elem.course);
  30. })

Array.prototype.every()

测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。

注意:若收到一个空数组,此方法在一切情况下都会返回 true

  1. const isBelowThreshold = (currentValue) => currentValue < 40;
  2. const array1 = [1, 30, 39, 29, 10, 13];
  3. console.log(array1.every(isBelowThreshold));
  4. // expected output: true

语法

  1. arr.every(callback(element, index, array), thisArg);

参数

  • callback:用来测试每个元素的函数

    • element:用来测试的当前值
    • index:可选,用来测试的当前值的索引
    • array:可选,当前数组
  • thisArg:执行 callback 时使用的 this 值。

返回值

如果回调函数的每一次返回都为 truthy 值,返回 true ,否则返回 false

描述

  • every 方法为数组中的每个元素执行一次 callback 函数,直到它找到一个会使 callback 返回 falsy 的元素。
  • 如果发现了一个这样的元素,every 方法将会立即返回 false。否则,callback 为每一个元素返回 trueevery 就会返回 true
  • callback 只会为那些已经被赋值的索引调用。不会为那些被删除或从未被赋值的索引调用。
  • 如果为 every 提供一个 thisArg 参数,则该参数为调用 callback 时的 this 值。如果省略该参数,则 callback 被调用时的 this 值,在非严格模式下为全局对象,在严格模式下传入 undefined
  • every 不会改变原数组。
  • every 和数学中的”所有”类似,当所有的元素都符合条件才会返回true。正因如此,若传入一个空数组,无论如何都会返回 true

示例

检测所有数组元素的大小

  1. //检测数组中的所有元素是否都大于 10。
  2. function isBigEnough(element, index, array) {
  3. return element >= 10;
  4. }
  5. [12, 5, 8, 130, 44].every(isBigEnough); // false
  6. [12, 54, 18, 130, 44].every(isBigEnough); // true
  7. //箭头函数形式
  8. [12, 5, 8, 130, 44].every(x => x >= 10); // false
  9. [12, 54, 18, 130, 44].every(x => x >= 10); // true

分析every

  1. //分析every
  2. var res = courseData.every(function (elem, index, array) {
  3. //elem.is_free == "0" -> 收费课
  4. //情况1:只打印一条数据且因不满足返回false
  5. //这里是第一条不满足条件的数据(免费课)
  6. console.log(elem);
  7. return elem.is_free == "0";
  8. //情况2:打印所有数据且因满足返回true
  9. console.log(elem);
  10. return elem.is_free;
  11. });
  12. console.log(res); // false/true

重写

  1. /**
  2. * 重写every()
  3. * 特点:
  4. * 1. 如果有一个不满足条件就停止遍历,条件就是return后面表达式
  5. * 2. 返回布尔值
  6. *
  7. * @返回值 返回满足条件为true
  8. * @返回值 返回不满足条件为false
  9. *
  10. * @参数1: 回调函数
  11. * @参数2: 可更改this指向,默认为window(可选)
  12. * @回调函数参数1: 元素
  13. * @回调函数参数2: 索引(可选)
  14. * @回调函数参数3: 数组本身(可选)
  15. *
  16. * 要求:
  17. * 1.必须数组调用
  18. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  19. * 3.兼容IE和es3
  20. */
  21. //封装myEvery
  22. Array.prototype.myEvery = function (fn) {
  23. var arr = this,
  24. //兼容es3只能for循环
  25. len = arr.length,
  26. //第二参数可传可不传利用arguments[1]
  27. //传了指向arg2, 没传指向window
  28. arg2 = arguments[1] || window,
  29. //初始化返回值结果
  30. res = true;
  31. for (var i = 0; i < len; i++) {
  32. //判断回调函数的返回值是真或假
  33. if (!fn.apply(arg2, [arr[i], i, arr])) {
  34. res = false;
  35. break;
  36. }
  37. }
  38. return res;
  39. };
  40. //参数1:回调函数fn
  41. var fn = function (elem, index, array) {
  42. return elem.is_free == "0";
  43. };
  44. //使用myEvery
  45. var result = courseData.myEvery(fn, {
  46. name: "test:",
  47. });
  48. console.log(result); //false

Array.prototype.some()

测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。

注意:如果用一个空数组进行测试,在任何情况下它返回的都是false

  1. const array = [1, 2, 3, 4, 5];
  2. // checks whether an element is even
  3. const even = (element) => element % 2 === 0;
  4. console.log(array.some(even));
  5. // expected output: true

语法

  1. arr.some(callback(element, index, array), thisArg);

参数

  • callback:用来测试每个元素的函数

    • element:数组上正在处理的元素
    • index:可选,数组中正在处理的元素的索引值
    • array:可选,当前数组
  • thisArg:可选,执行 callback 时使用的 this 值。

返回值

数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false。

描述

  • some() 为数组中的每一个元素执行一次 callback 函数,直到找到一个使得 callback 返回一个“真值”(即可转换为布尔值 true 的值)。
  • 如果找到了这样一个值,some() 将会立即返回 true。否则,some() 返回 false
  • callback 只会在那些”有值“的索引上被调用,不会在那些被删除或从来未被赋值的索引上调用。

示例

测试数组元素的值

  1. //检测在数组中是否有元素大于 10。
  2. function isBiggerThan10(element, index, array) {
  3. return element > 10;
  4. }
  5. [2, 5, 8, 1, 4].some(isBiggerThan10); // false
  6. [12, 5, 8, 1, 4].some(isBiggerThan10); // true
  7. //箭头函数形式
  8. [2, 5, 8, 1, 4].some(x => x > 10); // false
  9. [12, 5, 8, 1, 4].some(x => x > 10); // true

判断数组元素中是否存在某个值

  1. //模仿 includes() 方法, 若元素在数组中存在, 则回调函数返回值为 true
  2. var fruits = ['apple', 'banana', 'mango', 'guava'];
  3. function checkAvailability(arr, val) {
  4. return arr.some(function(arrVal) {
  5. return val === arrVal;
  6. });
  7. }
  8. checkAvailability(fruits, 'kela'); // false
  9. checkAvailability(fruits, 'banana'); // true
  10. //箭头函数形式
  11. var fruits = ['apple', 'banana', 'mango', 'guava'];
  12. function checkAvailability(arr, val) {
  13. return arr.some(arrVal => val === arrVal);
  14. }
  15. checkAvailability(fruits, 'kela'); // false
  16. checkAvailability(fruits, 'banana'); // true

将任意值转换为布尔类型

  1. var TRUTHY_VALUES = [true, 'true', 1];
  2. function getBoolean(value) {
  3. 'use strict';
  4. if (typeof value === 'string') {
  5. value = value.toLowerCase().trim();
  6. }
  7. return TRUTHY_VALUES.some(function(t) {
  8. return t === value;
  9. });
  10. }
  11. getBoolean(false); // false
  12. getBoolean('false'); // false
  13. getBoolean(1); // true
  14. getBoolean('true'); // true

重写

  1. /**
  2. * 重写some()
  3. * 特点:
  4. * 1. 如果有一个满足条件就停止遍历,条件就是return后面表达式
  5. * 2. 返回布尔值
  6. *
  7. * @返回值 返回任一满足条件为true
  8. * @返回值 返回所有不满足条件为false
  9. *
  10. * @参数1: 回调函数
  11. * @参数2: 可更改this指向,默认为window(可选)
  12. * @回调函数参数1: 元素
  13. * @回调函数参数2: 索引(可选)
  14. * @回调函数参数3: 数组本身(可选)
  15. *
  16. * 要求:
  17. * 1.必须数组调用
  18. * 2.第二参数必须为强制进行对象包装不包括undefined和null, 因为this必须指向对象
  19. * 3.兼容IE和es3
  20. */
  21. //封装mySome
  22. Array.prototype.mySome = function (fn) {
  23. var arr = this,
  24. //兼容es3只能for循环
  25. len = arr.length,
  26. //第二参数可传可不传利用arguments[1]
  27. //传了指向arg2, 没传指向window
  28. arg2 = arguments[1] || window,
  29. //初始化返回值结果
  30. res = false;
  31. for (var i = 0; i < len; i++) {
  32. //判断回调函数的返回值是真或假
  33. if (fn.apply(arg2, [arr[i], i, arr])) {
  34. res = true;
  35. break;
  36. }
  37. }
  38. return res;
  39. };
  40. //参数1:回调函数fn
  41. var fn = function (elem, index, array) {
  42. return elem.is_free == "0";
  43. };
  44. //使用mySome
  45. var result = courseData.mySome(fn, {
  46. name: "test:",
  47. });
  48. console.log(result); //true

Array.prototype.slice.call(arguments)

能将有length属性的对象转换为数组

类似ES6的Array.of()方法

  1. function list() {
  2. return Array.prototype.slice.call(arguments);
  3. }
  4. console.log(list('123'));
  5. //["123"]
  6. console.log(list(1));
  7. //[1]
  8. console.log(list(1, 2, 3));
  9. //[1, 2, 3]
  10. console.log(list(true));
  11. //[true]
  12. console.log(list(undefined));
  13. //[undefined]
  14. console.log(list(null));
  15. //[null]
  16. console.log(list(NaN));
  17. //[NaN]
  18. console.log(list(0));
  19. //[0]
  20. console.log(list(false));
  21. //[false]
  22. console.log(list(function () {}));
  23. //[ƒ]
  24. console.log(list(new String('abc')));
  25. //[String]
  26. console.log(list(new Number(123)));
  27. //[Number]
  28. console.log(list(new Boolean(true)));
  29. //[Boolean]

Array.of()

ECMAScript 2015 ES6

创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。

  1. console.log(Array.of(7)); // [7]
  2. console.log(Array.of(1, 2, 3)); //[1, 2, 3]
  3. console.log(Array(7)); //[empty × 7]
  4. console.log(Array(1, 2, 3));; // [1, 2, 3]

语法

  1. Array.of(element0[, element1[, ...[, elementN]]])

参数

elementN:任意个参数,将按顺序成为返回数组中的元素。

返回值

新的 Array 实例。

参数/返回值:

  1. console.log(Array.of('123'));; //["123"]
  2. console.log(Array.of(1)); // [1]
  3. console.log(Array.of(1, 2, 3)); // [1, 2, 3]
  4. console.log(Array.of(true)); //[true]
  5. console.log(Array.of(undefined)); //[undefined]
  6. console.log(Array.of(null)); //[null]
  7. console.log(Array.of(NaN)); //[NaN]
  8. console.log(Array.of(0)); //[0]
  9. console.log(Array.of(false)); //[false]
  10. console.log(Array.of({})); //[{…}]
  11. console.log(Array.of([])); //[Array(0)]
  12. console.log(Array.of(function () {})); //[ƒ]
  13. console.log(Array.of(new String('abc'))); //[String] 0: String {"abc" length: 1 __proto__: Array(0)
  14. console.log(Array.of(new Number(123))); //[Number] 0: Number {123} length: 1 __proto__: Array(0)
  15. console.log(Array.of(new Boolean(true))); //[Boolean] 0: Boolean {true} length: 1 __proto__: Array(0)

兼容写法:

  1. if (!Array.of) {
  2. Array.of = function() {
  3. return Array.prototype.slice.call(arguments);
  4. };
  5. }
  1. function list() {
  2. return Array.prototype.slice.call(arguments);
  3. }
  4. console.log(list('123'));
  5. //["123"]
  6. console.log(list(1));
  7. //[1]
  8. console.log(list(1, 2, 3));
  9. //[1, 2, 3]
  10. console.log(list(true));
  11. //[true]
  12. console.log(list(undefined));
  13. //[undefined]
  14. console.log(list(null));
  15. //[null]
  16. console.log(list(NaN));
  17. //[NaN]
  18. console.log(list(0));
  19. //[0]
  20. console.log(list(false));
  21. //[false]
  22. console.log(list(function () {}));
  23. //[ƒ]
  24. console.log(list(new String('abc')));
  25. //[String]
  26. console.log(list(new Number(123)));
  27. //[Number]
  28. console.log(list(new Boolean(true)));
  29. //[Boolean]

Array.from()

ECMAScript 2015 ES6

从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

  1. console.log(Array.from('foo'));
  2. //["f", "o", "o"]
  3. console.log(Array.from([1, 2, 3], x => x + x));
  4. //[2, 4, 6]

语法

  1. Array.from(arrayLike, mapFn, thisArg);

参数

  • arrayLike:想要转换成数组的伪数组对象或可迭代对象。
  • mapFn:如果指定了该参数,新数组中的每个元素会执行该回调函数。
  • thisArg:可选参数,执行回调函数 mapFnthis 对象。

返回值

一个新的数组实例。

Array.from() 可以通过以下方式来创建数组对象:

  • 伪数组对象(拥有一个 length 属性和若干索引属性的任意对象)
  • 可迭代对象(可以获取对象中的元素,如 Map和 Set 等)
  1. //参数是一个数组
  2. //返回一个新的数组引用
  3. const arr = [1, 2, 3];
  4. const newArr = Array.from(arr);
  5. console.log(newArr); //[1, 2, 3]
  6. console.log(arr === newArr); //false
  1. //参数是一个带有引用类型元素的数组
  2. //返回的新数组是一个浅拷贝
  3. const arr = [{
  4. id: 1,
  5. name: 'zhangsan'
  6. },
  7. {
  8. id: 2,
  9. name: 'lisi'
  10. },
  11. {
  12. id: 3,
  13. name: 'wangwu'
  14. }
  15. ]
  16. const newArr = Array.from(arr);
  17. console.log(newArr);
  18. console.log(arr[1] === newArr[1]); //true
  19. /**
  20. * (3) [{…}, {…}, {…}]
  21. * 0: {id: 1, name: "zhangsan"}
  22. * 1: {id: 2, name: "lisi"}
  23. * 2: {id: 3, name: "wangwu"}
  24. * length: 3
  25. * __proto__: Array(0)
  26. */
  1. //参数是一个字符串
  2. //字符串底层new String出来也具有可迭代对象
  3. const str = '123';
  4. const newArr = Array.from(str);
  5. console.log(newArr);
  6. //["1", "2", "3"]
  7. console.log(new String('123'));
  8. /**
  9. * String {"123"}
  10. * 0: "1"
  11. * 1: "2"
  12. * 2: "3"
  13. * length: 3
  14. * __proto__: String
  15. * Symbol(Symbol.iterator): ƒ [Symbol.iterator]()
  16. */

参数1/返回值:

  • 参数为空,报错
  • 参数如果是一个undefinednull,报错
  • 参数如果为空,报错
  • 参数如果是一个Symbol,不做处理返回一个空数组
  • 参数如果是一个数字,不做处理返回一个空数组
  • 参数如果是一个布尔值,不做处理返回一个空数组
  • 参数如果是一个正则,不做处理返回一个空数组
  • 参数如果是一个普通对象,不做处理返回一个空数组
  • 参数如果是一个数组,不做处理返回一个空数组
  1. console.log(Array.from());
  2. //Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
  3. console.log(Array.from(Symbol('123')));
  4. //[]
  5. console.log(Array.from(123));
  6. //[]
  7. console.log(Array.from('123'));
  8. //["1", "2", "3"]
  9. console.log(Array.from(true));
  10. //[]
  11. console.log(Array.from(false));
  12. //[]
  13. console.log(Array.from(/123/));
  14. //[]
  15. console.log(Array.from(undefined));
  16. //Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
  17. console.log(Array.from(null));
  18. //Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
  19. console.log(Array.from(NaN));
  20. //[]
  21. console.log(Array.from(0));
  22. //[]
  23. console.log(Array.from({}));
  24. //[]
  25. console.log(Array.from([]));
  26. //[]
  27. console.log(Array.from(new String('abc')));
  28. //["a", "b", "c"]
  29. console.log(Array.from(new Number(456)));
  30. //[]
  31. console.log(Array.from(new Boolean(true)));
  32. //[]
  1. //参数为类数组 依赖length
  2. const arrLike = {
  3. 0: 1,
  4. 1: 2,
  5. 2: 3,
  6. length: 3
  7. }
  8. console.log(Array.from(arrLike));
  9. //[1, 2, 3]
  10. //键名一定要按照数组对应下标的数字
  11. const arrLike2 = {
  12. a: 1,
  13. b: 2,
  14. c: 3,
  15. length: 3
  16. }
  17. console.log(Array.from(arrLike2));
  18. //[undefined, undefined, undefined]

类数组正常返回一个对应的数组的必要条件:

  • 键名必须冲0开始按数字顺序排列
  • length属性必须正确
  • 长度决定了新数组的长度,属性名决定了填充该数组的位置

从 Map 生成数组:

  1. //参数是一个Map
  2. const m = new Map([
  3. ['a', 1],
  4. ['b', 2],
  5. ['c', 3]
  6. ]);
  7. console.log(m);
  8. /**
  9. * Map(3) {"a" => 1, "b" => 2, "c" => 3}
  10. * [[Entries]]
  11. * 0: {"a" => 1}
  12. * key: "a"
  13. * value: 1
  14. * 1: {"b" => 2}
  15. * 2: {"c" => 3}
  16. * size: (...)
  17. * __proto__: Map
  18. */
  19. console.log(Array.from(m));
  20. /**
  21. * (3) [Array(2), Array(2), Array(2)]
  22. * 0: (2) ["a", 1]
  23. * 1: (2) ["b", 2]
  24. * 2: (2) ["c", 3]
  25. * length: 3
  26. * __proto__: Array(0)
  27. */

从 Set 生成数组:

  1. //参数是一个Set
  2. const s = new Set([1, 2, 3, 4]);
  3. console.log(s);
  4. /**
  5. * Set(4) {1, 2, 3, 4}
  6. * [[Entries]]
  7. * 0: 1
  8. * 1: 2
  9. * 2: 3
  10. * 3: 4
  11. * size: (...)
  12. * __proto__: Set
  13. */
  14. console.log(Array.from(s));
  15. //[1, 2, 3, 4]

参数2/参数3/返回值:

从类数组对象(arguments)生成数组:

  1. /**
  2. * Array.from()
  3. * @arguments[0] 必填 第一个参数必须要是可迭代对象或者标准的类数组
  4. * @arguments[1] 第二个参数为回调函数
  5. * @arguments[2] 第三个参数为可以更改回调内this指向
  6. * @item 当前遍历的元素
  7. * @index 当前遍历的元素在数组中对应的下标
  8. * @this 默认指向window 严格模式为undefined
  9. */
  10. const arrLike = {
  11. 0: 1,
  12. 1: 2,
  13. 2: 3,
  14. length: 3
  15. }
  16. const newArr = Array.from(arrLike, function (item, index, arr) {
  17. //每一次遍历必须返回一个值
  18. //由于回调执行的时候,Array.from还没有执行完毕,所以不存在逻辑上的新数组
  19. //所以无法在回调里获取到新数组本身(有别于数组的其他遍历方法)
  20. console.log(item); //1 2 3
  21. console.log(index); //0 1 2
  22. console.log(arr); //undefined
  23. console.log(this); //window
  24. return item + 1;
  25. }, {
  26. a: 1
  27. })
  28. console.log(newArr); //[2, 3, 4]
  1. //论Array.from()第二参数的执行原理
  2. const newArr = Array.from(arrLike).map(function (item, index, arr) {
  3. console.log(item, index, arr); //可打印
  4. return item + 1;
  5. });
  6. console.log(newArr); //[2, 3, 4]
  1. //证明from方法的第一个参数是必填项
  2. console.log(Array.from.length); //1

序列生成器(指定范围):

  1. //填充数组 - 序列生成器
  2. //range(start, end, 间隔)
  3. //[1, 3, 5, 7, 9];
  4. const r = range(1, 10, 2);
  5. function range(start, stop, step) {
  6. return Array.from({
  7. length: (stop - start) / step + 1
  8. }, function (item, index) {
  9. //1 + (0 * 2) = 1
  10. //1 + (1 * 2) = 3
  11. //1 + (2 * 2) = 5
  12. return start + (index * step);
  13. })
  14. }
  15. console.log(r);
  16. //[1, 3, 5, 7, 9]

数组去重合并:

  1. //数组的合并于去重
  2. function combine() {
  3. const arr = Array.prototype.concat.apply([], arguments);
  4. //Set集合结构本来有唯一性的特点
  5. return Array.from(new Set(arr));
  6. }
  7. const arr1 = [1, 2, 3, 4, 5];
  8. const arr2 = [2, 3, 4, 5, 6];
  9. const arr3 = [3, 4, 5, 6, 7];
  10. console.log(combine(arr1, arr2, arr3));
  11. //[1, 2, 3, 4, 5, 6, 7]
  1. //Array.from的源码实现
  2. //参数1:可迭代对象或者类数组 必填
  3. //参数2:mapFn 可选
  4. //参数3:this指向 可选
  5. Array.myFrom = (function () {
  6. //可不可以调用的函数
  7. const isCallable = function (fn) {
  8. return typeof fn === 'function' || Object.prototype.toString.call(fn) === '[object Function]';
  9. }
  10. //转换length 返回成正整数或者负整数
  11. const toInt = function (value) {
  12. const v = Number(value);
  13. //有可能转换出来的数字为非数字
  14. if (isNaN(v)) {
  15. return 0;
  16. }
  17. //!isFinite()不是无穷大的数
  18. if (v === 0 || !isFinite(v)) {
  19. return v;
  20. }
  21. //先取绝对值后向下取整
  22. return (v > 0 ? 1 : -1) * Math.floor(Math.abs(v));
  23. }
  24. //最大length的范围
  25. //常识:2的53次幂为JS最大的安全正整数
  26. const maxSafeInt = Math.pow(2, 53) - 1;
  27. const toLength = function (value) {
  28. const len = toInt(value);
  29. return Math.min(Math.max(len, 0), maxSafeInt);
  30. }
  31. return function (arrayLike) {
  32. //保持调用方
  33. //Array.myFrom
  34. const caller = this;
  35. if (arrayLike === null) {
  36. throw new TypeError('Method from requires an array-like object');
  37. }
  38. //包装arrayLike对象
  39. const origin = Object(arrayLike);
  40. //改变this指向的参数
  41. let arg2;
  42. //有传第二个参数 or 生成 undefined
  43. const mapFn = arguments.length > 1 ? arguments[1] : void undefined;
  44. if (typeof mapFn !== 'undefined') {
  45. //不可调用
  46. if (!isCallable(mapFn)) {
  47. throw new TypeError('mapFn must be a function');
  48. }
  49. //传递第三个参数
  50. if (arguments.length > 2) {
  51. arg2 = arguments[2];
  52. }
  53. }
  54. const len = toLength(origin.length);
  55. const arr = isCallable(caller) ? Object(new caller(len)) : new Array(len);
  56. let i = 0,
  57. val;
  58. while (i < len) {
  59. val = origin[i];
  60. if (mapFn) {
  61. arr[i] = typeof arg2 === 'undefined' ? mapFn(val, i) : mapFn.apply(arg2, [val, i]);
  62. } else {
  63. arr[i] = val;
  64. }
  65. i++;
  66. }
  67. return arr;
  68. }
  69. })();
  70. const arrLike = {
  71. 0: 1,
  72. 1: 2,
  73. 2: 3,
  74. length: 3
  75. }
  76. const newArr = Array.myFrom(arrLike);
  77. console.log(newArr); //[1, 2, 3]
  78. const newArr2 = Array.myFrom(arrLike, function (item, index) {
  79. console.log(item);
  80. console.log(index);
  81. return item + 1;
  82. });
  83. console.log(newArr2); //[2, 3, 4]

字符串方法

String.prototype.split()

使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。

  • 返回值

    • 返回源字符串以分隔符出现位置分隔而成的一个 Array
  • 参数

    • separator:指定表示每个拆分应发生的点的字符串。
  1. //join();
  2. //默认逗号隔开元素
  3. //跟toString()一样
  4. var arr = ['a', 'b', 'c', 'd'];
  5. var str1 = arr.join();
  6. var str2 = arr.toString();
  7. console.log(str1); //a,b,c,d
  8. console.log(str2); //a,b,c,d
  9. //参数
  10. //指定隔开符号
  11. console.log(arr.join('')); //abcd
  12. console.log(arr.join('-')); //a-b-c-d
  13. console.log(arr.join('&')); //a&b&c&d
  14. console.log(arr.join(0)); //a0b0c0d
  1. //split();
  2. //split()默认不传参可以把字符串转为数组
  3. //join('-') 和 split('-') 保持分隔符一致才能分开数字元素
  4. var arr = ['a', 'b', 'c', 'd'];
  5. var str1 = arr.join('-');
  6. var arr1 = str1.split();
  7. console.log(str1); //a-b-c-d
  8. console.log(arr1); //["a-b-c-d"]
  9. console.log('--------------------------------------');
  10. //参数1
  11. //参数传入'-'可以分割数组元素
  12. //参数传入',' 不可以分割数组元素
  13. //参数传入'' 分割数组元素
  14. var str2 = arr.join('-');
  15. var arr2 = str2.split('-');
  16. var arr3 = str2.split(',');
  17. var arr4 = str2.split('');
  18. console.log(str2); //a-b-c-d
  19. console.log(arr2); //["a", "b", "c", "d"]
  20. console.log(arr3); //["a-b-c-d"]
  21. console.log(arr4); //["a", "-", "b", "-", "c", "-", "d"]
  22. console.log('--------------------------------------');
  23. //参数2
  24. //传入数字 截断下标号之前(不包括)
  25. var str3 = arr.join('-');
  26. var arr5 = str3.split('-', 4);
  27. var arr6 = str3.split('-', 3);
  28. var arr7 = str3.split('-', 2);
  29. var arr8 = str3.split('-', 1);
  30. console.log(str3); //a-b-c-d
  31. console.log(arr5); //["a", "b", "c", "d"]
  32. console.log(arr6); //["a", "b", "c"]
  33. console.log(arr7); //["a", "b"]
  34. console.log(arr8); //["a"]
  1. const str = 'The quick brown fox jumps over the lazy dog.';
  2. const words = str.split(' ');
  3. console.log(words);
  4. //["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
  5. console.log(words[3]);
  6. // expected output: "fox"
  7. const chars = str.split('');
  8. console.log(chars);
  9. //["T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "t", "h", "e", " ", "l", "a", "z", "y", " ", "d", "o", "g", "."]
  10. console.log(chars[8]);
  11. // expected output: "k"
  12. const strCopy = str.split();
  13. console.log(strCopy);
  14. //["The quick brown fox jumps over the lazy dog."]
  15. console.log(strCopy[0]);
  16. // expected output: Array ["The quick brown fox jumps over the lazy dog."]

传参/返回值:

  • 传入[],返回包含逗号的所有数组元素
  • 传入跟join()一样的参数时会返回逗号分割的数组元素
  • join()传入参数且split()没有传参会返回字符串转数组的结果
  1. var arr = ['a', 'b', 'c'];
  2. console.log(arr, arr.join(), arr.join().split('e'));
  3. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  4. console.log(arr, arr.join(), arr.join().split(5));
  5. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  6. console.log(arr, arr.join(), arr.join().split(true));
  7. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  8. console.log(arr, arr.join(), arr.join().split(undefined));
  9. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  10. console.log(arr, arr.join(), arr.join().split(null));
  11. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  12. console.log(arr, arr.join(), arr.join().split(NaN));
  13. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  14. console.log(arr, arr.join(), arr.join().split(0));
  15. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  16. console.log(arr, arr.join(), arr.join().split(false));
  17. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  18. console.log(arr, arr.join(), arr.join().split({}));
  19. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  20. //连逗号也分割
  21. console.log(arr, arr.join(), arr.join().split([]));
  22. //["a", "b", "c"] "a,b,c" (5) ["a", ",", "b", ",", "c"]
  23. console.log(arr, arr.join(), arr.join().split(function () {}));
  24. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  25. console.log(arr, arr.join(), arr.join().split(new String('123')));
  26. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  27. console.log(arr, arr.join(), arr.join().split(new Number(123)));
  28. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  29. console.log(arr, arr.join(), arr.join().split(new Boolean(true)));
  30. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  31. console.log(arr, arr.join(), arr.join().split('&'));
  32. //["a", "b", "c"] "a,b,c" ["a,b,c"]
  33. console.log(arr, arr.join('&'), arr.join('&').split('&'));
  34. //["a", "b", "c"] "a&b&c" (3) ["a", "b", "c"]
  35. console.log(arr, arr.join('&'), arr.join('&').split());
  36. //["a", "b", "c"] "a&b&c" ["a&b&c"]
  37. console.log(arr, arr.join('-'), arr.join('-').split('-'));
  38. //["a", "b", "c"] "a-b-c" (3) ["a", "b", "c"]
  39. console.log(arr, arr.join('-'), arr.join('-').split());
  40. //["a", "b", "c"] "a-b-c" ["a-b-c"]
  41. console.log(arr, arr.join(''), arr.join('').split(''));
  42. //["a", "b", "c"] "abc" (3) ["a", "b", "c"]
  43. console.log(arr, arr.join(''), arr.join('').split());
  44. //["a", "b", "c"] "abc" ["abc"]
  45. console.log(arr, arr.join(' '), arr.join(' ').split(' '));
  46. //["a", "b", "c"] "a b c" (3) ["a", "b", "c"]
  47. console.log(arr, arr.join(' '), arr.join(' ').split());
  48. //["a", "b", "c"] "a b c" ["a b c"]

String.prototype.valueOf()

返回 String 对象的原始值

  1. const stringObj = new String('foo');
  2. console.log(stringObj);
  3. // expected output: String { "foo" }
  4. console.log(stringObj.valueOf());
  5. // expected output: "foo"

语法

  1. str.valueOf()

返回值

返回 String 对象的原始值

参数/返回值:

  1. console.log(new String('Hello world'), new String('Hello world').valueOf());
  2. //String {"Hello world"} "Hello world"
  3. console.log(new String('123456'), new String('123456').valueOf());
  4. //String {"123456"} "123456"
  5. console.log(new String(123456), new String(123456).valueOf());
  6. //String {"123456"} "123456"
  7. console.log(new Number(123456), new Number(123456).valueOf());
  8. //Number {123456} 123456
  9. console.log(new String(true), new String(true).valueOf());
  10. //String {"true"} 0: "t"1: "r"2: "u"3: "e" length: 4__proto__: String[[PrimitiveValue]]: "true" "true"
  11. console.log(new String(false), new String(false).valueOf());
  12. //String {"false"} 0: "f"1: "a"2: "l"3: "s"4: "e" length: 5__proto__: String[[PrimitiveValue]]: "false" "false"
  13. console.log(new String(undefined), new String(undefined).valueOf());
  14. //String {"undefined"} "undefined"
  15. console.log(new String(NaN), new String(NaN).valueOf());
  16. //String {"NaN"} 0: "N"1: "a"2: "N" length: 3__proto__: String[[PrimitiveValue]]: "NaN" "NaN"
  17. console.log(new String(null), new String(null).valueOf());
  18. //String {"null"} "null"
  19. console.log(new String(0), new String(0).valueOf());
  20. //String {"0"} "0"
  21. console.log(new String({}), new String({}).valueOf());
  22. //String {"[object Object]"}0: "["1: "o"2: "b"3: "j"4: "e"5: "c"6: "t"7: " "8: "O"9: "b"10: "j"11: "e"12: "c"13: "t"14: "]"length: 15 __proto__: String[[PrimitiveValue]]: "[object Object]" "[object Object]"
  23. console.log(new String([]), new String([]).valueOf());
  24. //String {""} length: 0 __proto__: String[[PrimitiveValue]]: ""
  25. console.log(new String(function () {}), new String(function () {}).valueOf());
  26. //String {"function () {}"} 0: "f"1: "u"2: "n"3: "c"4: "t"5: "i"6: "o"7: "n"8: " "9: "("10: ")"11: " "12: "{"13: "}" length: 14__proto__: String[[PrimitiveValue]]: "function () {}" "function () {}"

String.prototype.slice()

提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。

  1. const str = 'The quick brown fox jumps over the lazy dog.';
  2. console.log(str.slice(31));
  3. // expected output: "the lazy dog."
  4. console.log(str.slice(4, 19));
  5. // expected output: "quick brown fox"
  6. console.log(str.slice(-4));
  7. // expected output: "dog."
  8. console.log(str.slice(-9, -5));
  9. // expected output: "lazy"

语法

  1. str.slice(beginIndex, endIndex);

参数

  • beginIndex:从该索引(以 0 为基数)处开始提取原字符串中的字符。

    • 如果值为负数,会被当做 strLength + beginIndex 看待
  • endIndex:可选。在该索引(以 0 为基数)处结束提取字符串。

    • 如果省略该参数,slice() 会一直提取到字符串末尾。
    • 如果该参数为负数,则被看作是 strLength + endIndex 看待

返回值

返回一个从原字符串中提取出来的新字符串

使用 slice() 创建了一个新字符串。

  1. var str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
  2. str2 = str1.slice(1, 8),
  3. str3 = str1.slice(4, -2),
  4. str4 = str1.slice(12),
  5. str5 = str1.slice(30);
  6. console.log(str2); // 输出:he morn
  7. console.log(str3); // 输出:morning is upon u
  8. console.log(str4); // 输出:is upon us.
  9. console.log(str5); // 输出:""

使用 slice() 时传入了负值作为索引

  1. var str = 'The morning is upon us.';
  2. str.slice(-3); // 返回 'us.'
  3. str.slice(-3, -1); // 返回 'us'
  4. str.slice(0, -1); // 返回 'The morning is upon us'

String.prototype.substring()

返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。

语法

  1. str.substring(indexStart, indexEnd);

参数

  • indexStart:需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。
  • indexEnd:可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。

返回值

包含给定字符串的指定部分的新字符串。

描述

substring 提取从 indexStartindexEnd(不包括)之间的字符。特别地:

  • 如果 indexStart 等于 indexEndsubstring 返回一个空字符串。
  • 如果省略 indexEndsubstring 提取字符一直到字符串末尾。
  • 如果任一参数小于 0 或为 NaN,则被当作 0。
  • 如果任一参数大于 stringName.length,则被当作 stringName.length
  • 如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。
  1. var anyString = "Mozilla";
  2. // 输出 "Moz"
  3. console.log(anyString.substring(0,3));
  4. console.log(anyString.substring(3,0));
  5. console.log(anyString.substring(3,-3));
  6. console.log(anyString.substring(3,NaN));
  7. console.log(anyString.substring(-2,3));
  8. console.log(anyString.substring(NaN,3));
  9. // 输出 "lla"
  10. console.log(anyString.substring(4,7));
  11. console.log(anyString.substring(7,4));
  12. // 输出 ""
  13. console.log(anyString.substring(4,4));
  14. // 输出 "Mozill"
  15. console.log(anyString.substring(0,6));
  16. // 输出 "Mozilla"
  17. console.log(anyString.substring(0,7));
  18. console.log(anyString.substring(0,10));

运用 length 属性来使用 substring()

  1. // String.length 属性去获取指定字符串的倒数元素。显然这个办法更容易记住,因为你不再像上面那个例子那样去记住起始位置和最终位置。
  2. // Displays 'illa' the last 4 characters
  3. var anyString = 'Mozilla';
  4. var anyString4 = anyString.substring(anyString.length - 4);
  5. console.log(anyString4);
  6. // Displays 'zilla' the last 5 characters
  7. var anyString = 'Mozilla';
  8. var anyString5 = anyString.substring(anyString.length - 5);
  9. console.log(anyString5);

替换一个字符串的子字符串

  1. //替换了一个字符串中的子字符串。可以替换单个字符和子字符串。
  2. //该例结尾调用的函数将 "Brave New World" 变成了 "Brave New Web"
  3. function replaceString(oldS, newS, fullS) {
  4. // Replaces oldS with newS in the string fullS
  5. for (var i = 0; i < fullS.length; i++) {
  6. if (fullS.substring(i, i + oldS.length) == oldS) {
  7. fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
  8. }
  9. }
  10. return fullS;
  11. }
  12. replaceString("World", "Web", "Brave New World");
  1. //如果 oldS 是 newS 的子字符串将会导致死循环。例如,尝试把 "Web" 替换成 "OtherWorld"。一个更好的方法如下:
  2. function replaceString(oldS, newS,fullS){
  3. return fullS.split(oldS).join(newS);
  4. }

对象方法

Object.is()

判断两个值是否为同一个值

Object.is() 方法判断两个值是否为同一个值。如果满足以下条件则两个值相等:

  • 都是 undefined
  • 都是 null
  • 都是 true 或 false
  • 都是相同长度的字符串且相同字符按相同顺序排列
  • 都是相同对象(意味着每个对象有同一个引用)
  • 都是数字且

    • 都是 +0
    • 都是 -0
    • 都是 NaN
    • 或都是非零而且非 NaN 且为同一个

与== 运算不同。 == 运算符在判断相等前对两边的变量(如果它们不是同一类型) 进行强制转换 (这种行为的结果会将 “” == false 判断为 true), 而 Object.is不会强制转换两边的值。

与=== 运算也不相同。 === 运算符 (也包括 == 运算符) 将数字 -0 和 +0 视为相等 ,而将Number.NaN 与NaN视为不相等.

JS中相等性判断

ES6版本,四种相等判断的算法

  1. //全等 三等 ===
  2. //等于 ==
  3. //零值相等 -0 === +0
  4. //同值相等 -0 !== +0 NaN === NaN
  1. //JS中提供有关相等判断的操作方法
  2. //严格相等 === Strict Equality
  3. //非严格相等(抽象/非约束) 相等 == Loose(自由的,不受限制的) Equality
  4. //Object.is(v1, v2); ES6新API, 判断两个参数是否是同一个值
  5. // === 严格相等
  6. //不进行隐式类型转换 - 类型相同/值也相同
  7. // 1 === '1' ? false 1 === 2 ? false
  8. //引用值必须是同一个地址
  9. //var obj = {} obj === obj ? true {} === {} ? false
  10. //两个NaN 或者是 NaN跟其他值都不相等
  11. //NaN === NaN ? false NaN === undefined ? false
  12. //+0 和 -0 相等
  13. //+0 === -0 ? true
  14. //+ Infinity 与 - Infinity 相等
  15. //+ Infinity === - Infinity ? false
  16. //如何定义变量a a !== a -> true -> NaN
  17. //非严格相等 Abstract equality
  18. //隐式类型转换 - 等式两边都有可能被转换
  19. //转换以后还是用严格相等来比较
  20. //ToPrimitive(A)通过尝试调用 A 的A.toString() 和 A.valueOf() 方法,将参数 A 转换为原始值(Primitive)。
  21. //https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Equality_comparisons_and_sameness#%E9%9D%9E%E4%B8%A5%E6%A0%BC%E7%9B%B8%E7%AD%89
  22. //任何对象都与undefined null 不相等
  23. //窄对象 Narrow Object -> document.all[]
  24. //document.all == undefined
  25. //全等对结果的预测是更加清晰明确
  26. //全等在不隐式类型转换的前提下更快
  27. //1 '1' function
  28. //fasly值 8个
  29. //false 0 +/-0 8n '' "" `` null undefind NaN
  30. //同值相等 same-value
  31. //零值相等 same-value-zero +0 === -0
  32. //-0 !== +0 -> 同值相等
  33. //NaN === NaN -> 同值相等
  34. // var obj = {}
  35. // Object.defineProperty(obj, 'myZero'. {
  36. // value: -0,
  37. // writable: false,
  38. // configurable: false,
  39. // enumerable: false
  40. // });
  41. // //+0/0 都会抛出 异常,不能重新定义myZero属性
  42. // Object.defineProperty(obj, 'myZero', {
  43. // value: -0
  44. // })
  45. // Object.defineProperty(obj, 'myNaN', {
  46. // value: NaN,
  47. // writable: false,
  48. // configurable: false,
  49. // enumerable: false
  50. // })
  51. // Object.defineProperty(obj, 'myNaN', {
  52. // value: NaN
  53. // })
  1. //同值相等的底层实现 Object.is()
  2. //ES6抛出来的方法
  3. //ES5并没有暴露JS引擎的同值相等的方法
  4. //Object.is()
  5. //ES2015 ES6
  6. //同值相等的实现
  7. // var a = 1;
  8. // var b = '1';
  9. //false
  10. // var a = +0;
  11. // var b = -0;
  12. //false
  13. // var a = NaN;
  14. // var b = NaN;
  15. //true
  16. // var res = Object.is(a, b);
  17. // console.log(res); //false
  18. // var obj = {};
  19. //参数就是两个值,返回值就是通知相等判断的布尔结果
  20. // const res = Object.is(undefined, undefined);//true
  21. // const res = Object.is(null, null); //true
  22. // const res = Object.is(true, true); //true
  23. // const res = Object.is('1', '1'); //true
  24. // const res = Object.is(obj, obj); //true 同一引用
  25. // const res = Object.is({}, {}); //false 不同引用
  26. // const res = Object.is(1, 1); //true
  27. // const res = Object.is(+0, +0); //true
  28. // const res = Object.is(-0, -0); //true
  29. // console.log(res);
  30. //Object.is()的判断标准就是同值相等
  31. //-0 !== +0 -> 同值相等
  32. //NaN === NaN -> 同值相等
  33. //不进行隐式类型转换
  34. //-0 !== +0 -> 同值相等
  35. //NaN === NaN -> 同值相等

实现myIs()方法

  1. //实现myIs方法
  2. Object.myIs = function (a, b) {
  3. if (a === b) {
  4. return a !== 0 || 1 / a === 1 / b;
  5. }
  6. return a !== a && b !== b;
  7. }
  8. console.log(Object.myIs(1, 1)); //true
  9. console.log(Object.myIs({}, {})); //false
  10. console.log(Object.myIs(+0, -0)); //false
  11. console.log(1 / +0); //Infinity
  12. console.log(1 / -0); //-Infinity
  13. console.log('Infinity' === '-Infinity'); //false
  14. console.log((1 / +0) === (1 / -0)); //false
  15. console.log(Object.myIs(NaN, NaN)); //true