资讯专栏INFORMATION COLUMN

【js基础】js数组方法总结

aboutU / 2981人阅读

摘要:补充语言和宿主环境中许多新的内置函数,都提供了一个可选的参数,通常被称为上下文,其作用和一样,确保你的回调函数使用指定的。

补充:

JavaScript 语言和宿主环境中许多新的内置函数,都提供了一个可选的参数,通常被称为“上下文”(context),其作用和 bind(..) 一样,确保你的回调函数使用指定的 this。
function foo(el) {
 console.log( el, this.id );
}
var obj = {
 id: "awesome"
};
// 调用 foo(..) 时把 this 绑定到 obj
[1, 2, 3].forEach( foo, obj );
// 1 awesome 2 awesome 3 awesome
es5部分 1、map [es5]

不改变原数组
需要一个函数作为参数, 依次处理数组内每个元素,并返回新的值,无返回值则为undefined
使用所有的返回值组成新的数组

console.log(["a","b","c"].map((elem, index) => {
    console.log(elem, index)
    /*a 0
    *b 1
    *c 2
    */
    if (elem === "a") return "this is a"
}))// (3) ["this is a", undefined, undefined]  
2、filter [es5]

不改变原数组
需要一个函数作为参数, 依次便利每一个值,根据返回值生成新数组
返回真值 便利到的元素添加至新数组

console.log([ , 1, "", 2, undefined, 3, null, 4, 0, false, 5, true, 6, new Date()].filter((elem, index) => {
    console.log(elem, index)
    return elem
})) // [1, 2, 3, 4, 5, true, 6, Tue Nov 28 2017 08:29:52 GMT+0800 (中国标准时间)]
3、every [es5] some [es5]

语言太苍白,show you code
数组的every,和some方法,可参考下面两个函数实现的功能

const every = (fun, arr) => {
    for (let i = 0; i = arr.length; i ++) {
        if (!fun(arr[i], i)) return false    // 有结果为false, 立即返回false,不再继续遍历
    }
}
const some = (fun, arr) => {
    for (let i = 0; i < arr.length; i ++) {
        if (fun(arr[i], i)) return true      // 有结果为true, 立即返回true,不再继续遍历
    }
}
[0,1,2,3,4].filter(function (i) {if (i < 2){return 1}})  //[0, 1]
4、reduce [es5] reduceRight [es5]

功能描述参考下面代码

const reduce = (fun, arr, start) => {
    arr = arr.slice()
    start = start === undefined ? arr.shift() : start
    for (let i = 0; i < arr.length; i++) {   // 从左往右
        start = fun(start, arr[i])
    }
    return start
}
const reduceRight = (fun, arr, start) => {
    arr = arr.slice()
    start = start === undefined ? arr.pop() : start
    for (let i = arr.length - 1; i >= 0; i--) {   // 从右往左
        start = fun(start, arr[i])
    }
    return start
}
5、indexOf

返回某个指定的变量在数组中首次出现的位置

const a = {}
const b = [0, {}, 2, 3, "4", 4, 5, a, 4]
console.log(b.indexOf(a)) // 7
console.log(b.indexOf(4)) // 5
console.log(b.indexOf(4, "6")) // 8
console.log(b.indexOf("4")) // 4
6、lastIndexOf

返回某个指定的变量在数组中最后一次出现的位置

const a = {}
const b = [0, {}, 2, 3, "4", 4, 5, a, 4]
console.log(b.lastIndexOf(a)) // 7
console.log(b.lastIndexOf(4)) // 8
console.log(b.lastIndexOf(4, "6")) // 5
console.log(b.lastIndexOf("4")) // 4
es3部分 1、join [es3]

将数组拼接为字符串.

const b = [0, {}, 2, 3, "4", 4, 5, 4]
console.log(b.join()) // 0,[object Object],2,3,4,4,5,4
console.log(b.join(",")) // 0,[object Object],2,3,4,4,5,4   同b.join()
console.log(b.join("分割符")) //0分割符[object Object]分割符2分割符3分割符4分割符4分割符5分割符4

const a = [new Date(), null, undefined,[1, 2,3], [1, 2, 3], [[11, 12, 13], [21, 22, {a: [1,2,3]}]], {a: 1}]
console.log(a.join())      //Mon Nov 27 2017 15:39:01 GMT+0800 (中国标准时间),,,1,2,3,1,2,3,11,12,13,21,22,[object Object],[object Object]
console.log(a.toString())  //Mon Nov 27 2017 15:41:00 GMT+0800 (中国标准时间),,,1,2,3,1,2,3,11,12,13,21,22,[object Object],[object Object]
const testelema = new Date()
const testelemb = {}
const testelemc = []
testelema.toString = e => 1
testelemb.toString = e => 2
testelemc.toString = e => 3
console.log([testelema, testelemb, testelemc].join("-----"))   //1-----2-----3


const notfunction = {}
notfunction.toString = 1212
console.log([notfunction].join())  //Uncaught TypeError: Cannot convert object to primitive value

个人猜测,join会依次调用数组内元素的toString方法,并拼接成字符串,没有toString方法的元素返回空"",类似

const join = 
    (arr, delimiter = ",") => 
        arr.reduce((last, next) => {
            if (next === null || next === undefined) {
                return last + delimiter
            } else {
                if (typeof next.toString !== "function") {
                    throw new Error(`Cannot convert $ {typeof next}to primitive value `)
                }
                return last + delimiter + next.toString()
            }
        }, "")
        .replace(delimiter, "")
2、reverse [es3]

将数组中的元素颠倒顺序
该方法会直接改变原数组

const b = [true,"1",2,3,4,5]
b.reverse()
console.log(b.join())
3、sort [es3]

将数组的元素按照一定规则排序
该方法会直接改变原数组
参数类型必须为function
无参数的时候数组元素默认按照字母表顺序排序.

let b = [0,"a", 3,"3", 4,5,false]
console.log(b.sort().join()) //0,3,3,4,5,a,false

b = [0,"a", 3,"3", 4,5,false]
console.log(b.sort((elema, elemb) => {
    console.log(elema, elemb)
    /*
    * 0 "a"
    * a 3
    * 3 "3"
    * 3 4
    * 4 5
    * 5 false
    */
    console.log(typeof elema, typeof elemb)  //虽然上面打印出的字符串变量有的没有带引号,但是类型没错
    /*
    * number string
    * string number
    * number string
    * string number
    * number number
    * number boolean
    */
}).join())  //0,a,3,3,4,5,false  如果作为sort参数的方法,无返回值,则排序结果与不带参数相同

b = [10,"a",false, "20","11", 4,9]
console.log(b.sort((elema, elemb) => {
    if (typeof elema === "string" && typeof elemb === "number") {
        return -1   // 返回小于0的数则 elema在前  elemb在后 
    } else if (typeof elema === "number" && typeof elemb === "string") {
        return 1    // 返回大于0的数 则 elema在后  elemb在前
    }
    return 0; // 默认返回0   不加return 0结果一样
}).join()) // a,10,false,20,11,4,9   将字符串排在数字前面
4、concat [es3]

拼接数组
返回新数组,不改变原数组

const a = [1, 2, {a: 3}]
const b = a.concat([1,2,3,4])
console.log(b) //(7) [1, 2, {…}, 1, 2, 3, 4]
const c = a.concat([[1,2,3,4]])
console.log(c) // (4) [1, 2, {…}, Array(4)]
console.log(a) // (3) [1, 2, {…}]
const d = a.concat() 
console.log(d) // (3) [1, 2, {…}]      可以使用concat进行浅拷贝
d[0] = 10
console.log(d) // (3) [10, 2, {…}]
console.log(a) // (3) [1, 2, {…}]
d[2].a = 10
console.log(a[2].a)  //10
5、slice [es3]

返回数组的一个片段
返回新数组,不改变原数组
使用slice复制数组也是浅拷贝
两个参数时,包含序号为前一个参数的元素,不包含序号为后一个参数的元素
前一个参数默认为0
后一个参数默认为数组长度

const a = [0,1,2,3,4,5,6,7]
console.log(a.slice()) // (8) [0, 1, 2, 3, 4, 5, 6, 7]
console.log(a.slice(0)) // (8) [0, 1, 2, 3, 4, 5, 6, 7]
console.log(a.slice(0, a.length)) // (8) [0, 1, 2, 3, 4, 5, 6, 7]
console.log(a.slice(2))  // (6) [2, 3, 4, 5, 6, 7]
console.log(a.slice(2, a.length)) // (6) [2, 3, 4, 5, 6, 7]
console.log(a.slice(2, 3)) // [2]
console.log(a.slice(2, 4)) // (2) [2, 3]
console.log(a.slice(-2))  // (2) [6, 7]
console.log(a.slice(-2, a.length))  // (2) [6, 7]
console.log(a.slice(2, a.length - 1))  //(5) [2, 3, 4, 5, 6]
console.log(a.slice(2, - 1))   // (5) [2, 3, 4, 5, 6]
6、splice [es3]

从数组中删除元素、插入元素、或者同时完成这俩种操作.
splice直接修改数组

let a = [0,1,2,3,4,5,6,7]
a.splice()
console.log(a)  // (8) [0, 1, 2, 3, 4, 5, 6, 7]
a = [0,1,2,3,4,5,6,7]
a.splice(0)
console.log(a)  // []
a = [0,1,2,3,4,5,6,7]
a.splice(0, a.length)
console.log(a)  // []
a = [0,1,2,3,4,5,6,7]
a.splice(0, 1)
console.log(a)  // []
7、其余常用的es3方法这里就简单列一下,就不啰嗦了

push和pop
unshift和shift;
toString和toLocaleString

es6部分 1、copyWithin

这是一个我想不到应用场景的方法
大概我以后也很少用到
把数组自己的一部分复制到另一部分
参考如下代码

const copyWithin = (arr, target, start = 0, end = arr.length) => {
    const copy = arr.slice()
    start = start < 0 ? (start + arr.length) : start
    end = end < 0 ? (end + arr.length) : end
    for (let i = start; i < end; i ++) {  // 拷贝内容不包括end    end 小与 start 什么操作都不做且不报错
        arr[target + i - start] = copy[i]   // copyWithin修改原数组
    }
}
2、find

直接上polyfill

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, "find", {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError(""this" is null or not defined");
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== "function") {
        throw new TypeError("predicate must be a function");
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    }
  });
}

未完待续

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/90037.html

相关文章

  • JS程序

    摘要:设计模式是以面向对象编程为基础的,的面向对象编程和传统的的面向对象编程有些差别,这让我一开始接触的时候感到十分痛苦,但是这只能靠自己慢慢积累慢慢思考。想继续了解设计模式必须要先搞懂面向对象编程,否则只会让你自己更痛苦。 JavaScript 中的构造函数 学习总结。知识只有分享才有存在的意义。 是时候替换你的 for 循环大法了~ 《小分享》JavaScript中数组的那些迭代方法~ ...

    melody_lql 评论0 收藏0
  • 数组的使用总结— (js基础复习第2期)

    摘要:前一个值,当前值,索引,数组对象产生新数组的迭代器方法类似,对数组的每个元素使用某个函数,并返回新数组和相似,传入一个返回值为布尔类型的函数。 1. 前言 数组真的是每天用了,但是有很多方法都是记不住,总是要百度查,很烦,所以才写了个数组使用总结,有什么不对的希望大家指出来。 2. 思路 先看看这些问题都记得很清楚么? 创建数组,怎么创建数组的 数组的构造方法Array有哪些方法?E...

    zhigoo 评论0 收藏0
  • js基础归纳总结1

    摘要:局部变量在函数中声明的变量,会成为函数的局部变量。局部变量的作用域是局部的只能在函数内部访问它们。单独的情况下,指的是全局对象。在事件中,指的是接收事件的元素。布尔值提供一种布尔数据类型。所有不具有真实值的即为布尔值为零负零空值。 闭包 闭包的优点:1.可以读取函数内部的变量2.这些变量的值始终保持在内存中适用场景 作用域 作用域指的是有权访问的变量集合。在 JavaScript 中有...

    Jeff 评论0 收藏0
  • js 基础总结(常用的反转)

    摘要:中的反转中的反转主要有以下三种,数字反转,字符串反转,数组的反转数组的反转结果字符串的反转先将字符串转换为数组,然后反转数组,最后将数组转合并为字符串结果兼容性由于存在兼容性问题,的浏览器可以很好的使用,但是是个问题。 js中的反转 js中的反转主要有以下三种,数字反转,字符串反转,数组的反转 数组的反转 var arr = [1,2,3,4,5]; arr = arr.reverse...

    ACb0y 评论0 收藏0
  • JavaScript学习总结(一)基础部分

    摘要:前缀规范每个局部变量都需要有一个类型前缀,按照类型可以分为表示字符串。例如,表示以上未涉及到的其他对象,例如,表示全局变量,例如,是一种区分大小写的语言。布尔值与字符串相加将布尔值强制转换为字符串。 基本概念 javascript是一门解释型的语言,浏览器充当解释器。js执行时,在同一个作用域内是先解释再执行。解释的时候会编译function和var这两个关键词定义的变量,编译完成后从...

    AlanKeene 评论0 收藏0

发表评论

0条评论

aboutU

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<