js数组基本方法总结

来源:互联网 发布:苏州网络推广 编辑:程序博客网 时间:2024/06/07 23:54

先定义一个数组:

var a = ["a","b","c"];

数组检测

  • instanceof
console.log(a instanceof Array); // true

只有一个全局作用域下,使用这种方法。若网页中包含多个框架,容易出错。

  • Array.isArray()
console.log(Array.isArray(a)); // true

不管有几个全局环境,都可以,但是兼容性不高。

  • Object.prototype.toString.call()
console.log(Object.prototype.toString.call(a)); // [object Array]

使用对象的toString函数判断,兼容性好。不能使用数组自身的toString,因为该函数已经被重写了。

数组转换

数组转为字符串

  • toLocaleString
console.log(a.toLocaleString()); //a,b,c
  • toString
console.log(a.toString()); //a,b,c
  • valueOf
console.log(a.valueOf()); // 返回本身  ["a", "b", "c"]
  • join
console.log(a.join('&')); //a&b&c

由于前两个方法变成字符串默认中间加“,”,使用join方法,可以改变间隔符。

  • 扩展运算符(ES6新增)
    扩展运算符是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3]);// 1 2 3console.log(1, ...[2, 3, 4], 5);// 1 2 3 4 5[...document.querySelectorAll('div')];// [<div>, <div>, <div>]

其他数据结构转换为数组

  • 扩展运算符(ES6新增)
    扩展运算符支持将有遍历器接口的数据结构转换为数组。
// arguments对象function foo() {  var args = [...arguments];}// NodeList对象[...document.querySelectorAll('div')]
  • Array.from()(ES6新增)
    • 将有遍历器接口的数据结构转换为数组
    • 将类数组转换为数组
    • 第一个参数为要转换为数组的数据结构
    • 第二个参数为map函数,对转换的数组进行处理
  • Array.prototype.slice
    借用Array的方法将类数组转换为数组。
  • Array.of()(ES6新增)
    将一组值,转换为数组。
Array.of(3, 11, 8) // [3,11,8]Array.of(3) // [3]Array.of(3).length // 1

数组添加删除

栈方法

  • push

从末尾添加

console.log(a.push('d')); // 返回数组长度 4
  • pop
    从末尾移除
console.log(a.pop()); // 返回移除的项 d

队列方法

  • shift

从头部移除

console.log(a.shift()); // 返回移除的项 a
  • unshift
    从头部添加
console.log(a.unshift('a')); // 返回数组长度

数组排序

  • reverse
console.log(a.reverse()); // 反转 ["c", "b", "a"]
  • sort
console.log(a.sort()); // 排序,默认从小到大,但是排序前会调用toString

还可以传入函数:

var values = [0,10,5,1,15];function compare(value1,value2) {    return value1 - value2;}console.log(values.sort(compare));

数组操作

  • concat
    concat深入解析
  • slice
    slice深入解析

  • splice

始终返回被删除的项,若没有,返回空数组。
第一个参数表示起始位置;第二个参数表示要删除的个数(若为0,表示不删除);第三个参数表示要添加的项(可选);

var colors1 = ["red", "green", "blue"];console.log(colors1.splice(0,1)); //["red"]console.log(colors1); //["green", "blue"]console.log(colors1.splice(0,0,"aaa")); //[]console.log(colors1); //["aaa", "green", "blue"]console.log(colors1.splice(0,2,"sss")); //["aaa", "green"]console.log(colors1); //["sss", "blue"]
  • copyWithin()(ES6新增)
    在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。

    参数列表:

    • target(必需):从该位置开始替换数据。
    • start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
    • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
[1, 2, 3, 4, 5].copyWithin(0, 3);// [4, 5, 3, 4, 5]// 将3号位复制到0号位[1, 2, 3, 4, 5].copyWithin(0, 3, 4);// [4, 2, 3, 4, 5]// -2相当于3号位,-1相当于4号位[1, 2, 3, 4, 5].copyWithin(0, -2, -1);// [4, 2, 3, 4, 5]
  • fill()(ES6新增)
    使用给定值,填充一个数组。
    第一个参数表示填充的值,第二个参数表示填充起始位置,第三个参数 表示填充的结束位置的前一个。
['a', 'b', 'c'].fill(7);// [7, 7, 7]new Array(3).fill(7);// [7, 7, 7]['a', 'b', 'c'].fill(7, 1, 2);// ['a', 7, 'c']

查找数组

  • indexOf
    从前往后查找,返回查找项的位置,没有的话返回-1。

  • lastIndexOf
    从后往前查找,返回查找项的位置,没有的话返回-1。

  • findIndex()(ES6新增)
    返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

[1, 5, 10, 15].findIndex(function(value, index, arr) {  return value > 9;}) // 2

indexOf方法无法识别数组的NaN成员,但是findIndex方法可以借助Object.is方法做到。

[NaN].indexOf(NaN)// -1[NaN].findIndex(y => Object.is(NaN, y))// 0
  • find()(ES6新增)
    返回第一个符合条件的数组成员,如果所有成员都不符合条件,则返回undefined。
[1, 5, 10, 15].find(function(value, index, arr) {  return value > 9;}) // 10
  • includes()(ES6新增)
    返回一个布尔值,表示某个数组是否包含给定的值。
    第一个参数表示查找的值,第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置
[1, 2, 3].includes(2)     // true[1, 2, 3].includes(4)     // false[1, 2, NaN].includes(NaN) // true[1, 2, 3].includes(3, 3);  // false[1, 2, 3].includes(3, -1); // true

遍历数组

ES5

传入的第一个参数为函数,都有三个参数,item,index,array

  • every
    查询每一项是否都符合要求
  • filter
    筛选出符合要求的项
  • forEach
    做某些操作,没有返回值
  • map
    做某些操作,并且返回
  • some
    有一项符合要求就可以

ES6新增

它们都返回一个遍历器对象,可以用for…of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

  • entries()
  • keys()
  • values()
for (let index of ['a', 'b'].keys()) {  console.log(index);}// 0// 1for (let elem of ['a', 'b'].values()) {  console.log(elem);}// 'a'// 'b'for (let [index, elem] of ['a', 'b'].entries()) {  console.log(index, elem);}// 0 "a"// 1 "b"

也可以手动调用next()方法。

let letter = ['a', 'b', 'c'];let entries = letter.entries();console.log(entries.next().value); // [0, 'a']console.log(entries.next().value); // [1, 'b']console.log(entries.next().value); // [2, 'c']

归并方法

  • reduce
    从前向后迭代
    第一个参数为函数(参数为前一个值,当前值,索引,数组),从第二项开始迭代。每次迭代的prev为上一次迭代的结果。
var values = [1,2,3,4,5];var sum = values.reduce(function (prev, cur, index, array) {     return prev * cur;});console.log(sum); // 120  1*2*3*4*5

第二个参数为起始值。

var values = [1,2,3,4,5];var sum = values.reduce(function (prev, cur, index, array) {     return prev * cur;},2);console.log(sum); // 240  2*1*2*3*4*5
  • reduceRight
    从后向前迭代