阅读 71

数组常用方法总结

MDN

  1. 检测数组: isArray
  2. toString 返回数组的字符串表示,中间以逗号分隔
    注意:对于数组中的空位视为undefined,而undefined和null会被处理成空字符串

以下方法会影响到原数组

  1. push: 添加元素至数组末尾,return修改后的数组长度
  2. pop:在数组末尾弹出一项元素,return移除的项
  3. unshift:添加元素至数组前端,return修改后的数组长度
  4. shift:在数组前端弹出一项元素,return移除后的项
  5. reverse:反转数组项的顺序,return反转后的数组
  6. sort:排序。return排序后的数组
    默认:升序排列,默认调用每个元素的tostring方法,比较的是字符串的顺序
    可接收一个比较函数的参数:
    如果第一个参数应该位于第二个参数之前,则需要返回一个负数
    相等,返回0
    第一个参数应该位于第二个参数之后,则需要返回个正数
let test=[23,3,45,65,34]
function compare(a,b) {
    return a<b ? -1 : ((a>b) ? 1 : 0)
}
function compare2(a,b) {
    return a<b ? 1 : ((a>b) ? -1 : 0)
}
test.sort(compare) // [3, 23, 34, 45, 65]  升序
test.sort(compare2) // [65, 45, 34, 23, 3] 降序
  1. splice:具有多种用法,return一个从原数组中删除的项,若没有删除,返回的是一个空数组
    删除:splice(要删除的起始位置,要删除的结束位置(包括结束位置的项))
    插入:splice(起始位置,0(代表要删除的项数为0),要插入的项1,要插入的项2,要插入的项3···)
    替换:splice(起始位置,要删除的项数,要插入的项1,项2,项3···)
let array = ['a','b','c']
removed = array.splice(1,2)  // 包括结束位置的项   removed:["b", "c"]  array:["a"]

let array2= ['a','b','c']
removed = array2.splice(1,0,'d','e') // removed:[]  array2:["a", "d", "e", "b", "c"]

let array3= ['a','b','c']
removed = array3.splice(1,2,'d','e') // removed:["b", "c"]  array3:["a", "d", "e"]

10、copyWithin: 浅赋值数组的一部分到同一个数组的另一个位置,并返回它
arr.copyWithin(target, start, end) 不包括end

 [1, 2, 3, 4, 5].copyWithin(-2)
// [1, 2, 3, 1, 2]

[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(-2, -3, -1)
// [1, 2, 3, 3, 4]

11、fill: 利用一个固定值填充一个数组中从起始索引到终止索引内的全部元素,不包括终止索引

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}

// Objects by reference.
var arr = Array(3).fill({}) // [{}, {}, {}];
// 需要注意如果fill的参数为引用类型,会导致都执行都一个引用类型
// 如 arr[0] === arr[1] 为true
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

以下方法为不会影响原数组

1、concat:第一步会先创建当前数组的一个副本,然后将接受到的参数添加到这个副本的末尾,最后返回新构建的数据(创建的副本)

let colors = ['red','yellow','blue']
let colors2 = colors.concat('green', ['black','gray'])
let colors3 = colors.concat('green', ['black','gray',['aaa']])
colors // (3) ["red", "yellow", "blue"]
colors2 // (6) ["red", "yellow", "blue", "green", "black", "gray"]
colors3 // (7) ["red", "yellow", "blue", "green", "black", "gray", Array(1)]

2、slice :slice(返回项的起始位置,返回项的结束位置(不包括结束位置的项))

let colors = ["red", "yellow", "blue", "green", "black", "gray"]
let colors2 = colors.slice(1) // ["yellow", "blue", "green", "black", "gray"]
let colors3 = color.slice(1,2) // ["yellow"]
let colors4 = color.slice(1,5)// ["yellow", "blue", "green", "black"]
let colors5 = color.slice(-2,-1) // 若参数为负数,使用数组长度加上该数,即为6+(-2),6+(-1)   -> 4,5 -> ["black"]
let colors = color.slice(5,4) // // 若结束位置小于起始位置,返回空数组 -> []

3、indexOf:从数组的开头向后查找,
4、lastIndexOf:从数组的末尾向前查找
返回查找到的位置,没找到返回-1。内部查找时使用的是全等(===)

let colors = ["red", "yellow", "blue", "green", "black", "gray"]
colors.indexOf('yellow') // 1
colors.lastIndexOf('yellow') // 1

5、every:对数组中的每一项运行指定的函数,如果该函数的每一项都返回为true,则最终结果返回true(查询数组中的项是不是都符合条件)
注意:对于数组中的空值会跳过空位
6、some:对数组的每一项运行指定的函数,如果该函数的任意一项返回true,最终结果返回true(查询数组中是否存在某一个符合条件的项)
注意:对于数组中的空值会跳过空位
7、filter:对数组中的每一项运行指定的函数,最终会返回通过该函数(即返回true)的项组成的数组
注意:对于数组中的空值会跳过空位
8、forEach:对数组中的每一项运行指定的函数,无返回值(for循环)
注意:对于数组中的空值会跳过空位
9、map:对数组中的每一项运行指定的函数,return每次函数调用的结果组成的数组
注意:对于数组中的空值会跳过空位,但会保留这个值

let testarray = [21,0,5,6,34]
// item:当前值
// index:当前索引
// array:当前的数组
let result1 = testarray.every(function(item,index,array) {
  return (item>6)
})// result1: false
let result2 = testarray.some(function(item,index,array) {
  return (item>6)
})// result2: true
let result3 = testarray.filter(function(item,index,array) {
  return (item>6)
})// result3:[21, 34]
let result4 = testarray.map(function(item,index,array) {
  return (item*2)
})// result4: [42, 0, 10, 12, 68]

10、reduce/reduceRight迭代数组的所有项,构建一个最终返回的值。reduce:从数组的第一项。reduceRight:从数组的最后一项开始
注意:对于数组中的空值会跳过空位

// 基本用法
/*
pre:前一个值
cur:当前值
index:项的索引值
array:数据对象
第一次迭代:pre:21  cur:1
第二次迭代:pre:22 cur:5
第三次迭代:pre: 27 cur:6
*/
let testarray = [21,1,5,6,34]
let sum = testarray.reduce(function(pre,cur,index,array) {
  return (pre+cur)
})// sum:67

// 提供初始值用法:
// arr.reduce(function(pre, cur, index, arr), initValue)
/*
如果提供了初始值initValue,则pre会等于初始值,cur等于第一个元素
第一次迭代:pre: 20 cur:21
第二次迭代:pre:41 cur:1
第三次迭代:pre:42 cur:5
*/
let testarray = [21,1,5,6,34]
let sum = testarray.reduce(function(pre,cur,index,array) {
  return (pre+cur)
}, 20)// sum:87

11、entries: return一个新的Array Iterator对象,该对象包含数组中的每个索引的键值对

const array1 = ['a', 'b', 'c'];
const iterator1 = array1.entries();
iterator1.next().value //  [1, "b"]
iterator1.next().value // [2, "c"]

12、find:返回数组中满足提供的测试函数的第一个元素的值,否则返回undefined

// 语法:arr.find(callback(element,index, array), thisArg)
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10); // 12

13、findIndex: 返回数组中满足提供的测试函数的第一个元素的索引。未找到则返回-1

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // 3

14、flat:会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回(默认值为1)

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat()); // [0, 1, 2, 3, 4]
console.log(arr1); // [0, 1, 2, [3, 4]]

const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2)); // [0, 1, 2, [3, 4]]

15、flatMap 使用映射函数映射每个元素,然后将结果压缩成一个新数组

var arr1 = [1, 2, 3, 4];
arr1.map(x => [x * 2]);// [[2], [4], [6], [8]]
arr1.flatMap(x => [x * 2]);// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x => [[x * 2]]);// [[2], [4], [6], [8]]

let arr1 = ["it's Sunny in", "", "California"];
arr1.map(x => x.split(" "));// [["it's","Sunny","in"],[""],["California"]]
arr1.flatMap(x => x.split(" "));// ["it's","Sunny","in", "", "California"]

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

const array1 = [1, 2, 3];
console.log(array1.includes(2));// true

const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));//  true
console.log(pets.includes('at')); // false

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

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));//  1
// start from index 2 从指定位置后查找
console.log(beasts.indexOf('bison', 2));// 4
console.log(beasts.indexOf('giraffe'));//-1

18、join 将一个数组或类数组对象的所有元素连接成一个字符串并返回
注意:对于数组中的空位视为undefined,而undefined和null会被处理成空字符串

const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join('-'));//  "Fire-Air-Water"

19、keys 返回一个包含数组中每个索引键的Array Iterator对象

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
  console.log(key);
}  // 0,1,2

20、toLocaleString() 返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' }); // "1,a,12/21/1997, 2:12:00 PM"

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

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());// "1,2,a,1a"

22、values 返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值

const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
  console.log(value);
} // a,b,c

2021.07.22更新
数组自身方法:
1、Array.from() :将一个类数组或可迭代对象创建为一个新的,浅拷贝的数组实例。return一个新的数组实例

// Array.from(想要转换成数组的伪数组对象或可迭代对象, 回调函数)
// 参数中回调函数可选,可对新数组中的每个元素执行该函数
// 字符串
Array.from('foo');   // [ "f", "o", "o" ]
// set结构
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);// [ "foo", "bar", "baz" ]
// 数组去重
let arr = [1,2,5,5,56,9]
Array.from(new Set(arr))  // [1, 2, 5, 56, 9]

2、Array.isArray(): 判断传入的参数是否为数组
3、Array.of() :创建一个具有可变数量参数的新数组实例

Array.of(7)   // [7]
Array.of(1,2,3)   // [1,2,3]
// 区别
Array(7)   // [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]

作者:空白懒人

原文链接:https://www.jianshu.com/p/9640ef620588

文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐