Javascript的数组Array操作整理

2021-03-26 1045点热度 0人点赞 1条评论

数组Array是Javascript操作里用的很多的,本文整理下我平时用的多的关于array的操作方法,也会整理下最新的ES6关于Array的方法,这类写法比较简便简洁。

归类:

分类 方法
修改Array push()pop()shift()unshift()reverse()splice()sort()copyWithin()fill()
查询相关 lengthindexOf()lastIndexOf()find()findIndex()filter()
子元素处理 forEach()
产生新的Array 构造方法 join()concat()slice()map()reduce()reduceRight()
其他用法 every()some()includes()Array.isArray() keys()valuesentries

构造方法

var array = new Array();
var array = [1,2,3,4];
var array = ["a", "b", "c"];
var array = [{name: "Terry", age: 18}, {name: "Tom", age: 22}]

常用简单方法

let a = [1,2,3,4,5,6,7,8]; //得到数字长度 
console.log(a.length); // 8 

//indexOf lastIndexOf 
//查找某个元素在Array中的位置,lastIndexOf就是从后面往前面查,先查到就返回 //如果返回-1就说明没有找到 
let a = [1,2,3,4,5,6,7,8]; 
console.log(a.indexOf(4)); // 3 
console.log(a.indexOf(4,5)); // -1 ( 查找 5,6,7,8 沒有 4 ) 

//join用法。将数组的每个元素连起来 
let a = [1,2,3,4]; a.join(",");//转化成文本,用逗号分割 1,2,3,4 //Array.isArray判断是否是Array 
let a = [1,2,3,4,5,6,7,8]; 
let b = 123; let c = 'hello'; 
let d = {d1:1,d2:2}; 
console.log(Array.isArray(a)); // true 
console.log(Array.isArray(b)); // false 
console.log(Array.isArray(c)); // false 
console.log(Array.isArray(d)); // false

push

向数组的末尾添加一个或更多元素,并返回新的长度

let a = [1,2,3];
a.push(4);
a.push(5, 6);//可以多个
console.log(a);  // [1, 2, 3, 4, 5, 6]

pop

取出Array最后一个元素(原Array的最后一个元素就删除了)

let a = [1,2,3,4];
let b = a.pop();
console.log(a);  // [1, 2, 3]
console.log(b);  // 4

shift

取出Array最后一个元素(原Array的第一个元素就删除了)

let a = [1,2,3,4];
let b = a.shift();
console.log(a);  // [2, 3, 4]
console.log(b);  // 1

unshift

将指定的元素添加到第一个的位置,并返回新的长度。

let a = [1,2,3,4,5,6,7,8];
a.unshift(100,200,300);
console.log(a);  // [100, 200, 300, 1, 2, 3, 4, 5, 6, 7, 8]

reverse

顾名思义,就是翻转元素顺序

let a = [1,2,3,4];
a.reverse();
console.log(a); // [4, 3, 2, 1]

splice

可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。item1...可选,就变成删除

array.splice(index,howmany,item1,.....,itemX) 

let a = [1,2,3,4,5,6,7,8]; a.splice(5,1,100); 
console.log(a); // [1, 2, 3, 4, 5, 100, 7, 8] ( 6 被删除,100 加到第 5 个位置 ) 

let b = [1,2,3,4,5,6,7,8]; b.splice(5,3,100,200,300); 
console.log(b); // [1, 2, 3, 4, 5, 100, 200, 300] ( 6,7,8 被删除,100,200,300 加到第 5,6,7 个位置 ) 

let c = [1,2,3,4,5,6,7,8]; 
c.splice(5,0,100); 
console.log(c); // [1, 2, 3, 4, 5, 100, 6, 7, 8] ( 沒有元素被删除,100 加到第 5 个位置 ) 

let d = [1,2,3,4,5,6,7,8]; 
d.splice(5,1); 
console.log(d); // [1, 2, 3, 4, 5, 7, 8] ( 6 被移除了 )

sort

排序(ES5)

参数可选: 规定排序顺序的比较函数。

默认情况下sort()方法没有传比较函数的话,默认按字母升序,如果不是元素不是字符串的话,会调用toString()方法将元素转化为字符串的Unicode(万国码)位点,然后再比较字符。

// 字符串排列
var a = ["Banana", "Orange", "Apple", "Mango"];
a.sort(); // ["Apple","Banana","Mango","Orange"]

var a = [10, 1, 3, 20,25,8];
console.log(a.sort()) // [1,10,20,25,3,8];


let a = [1,3,8,4,5,7,6,2];
// 升序 x-y < 0 x将排到y的前面,按照x的大小来排序的 
a.sort((x,y) => y - x);
// or:
a.sort(function(x,y){
    return x-y;
});
console.log(a);   // [8, 7, 6, 5, 4, 3, 2, 1]
a.sort((x,y) => x - y);
console.log(a);   // [1, 2, 3, 4, 5, 6, 7, 8]

//数组多条件排序
var array = [{id:10,age:2},{id:5,age:4},{id:6,age:10},{id:9,age:6},{id:2,age:8},{id:10,age:9}];
array.sort(function(a,b){
    if(a.id === b.id){// 如果id的值相等,按照age的值降序
        return b.age - a.age
    }else{ // 如果id的值不相等,按照id的值升序
        return a.id - b.id
    }
})
// [{"id":2,"age":8},{"id":5,"age":4},{"id":6,"age":10},{"id":9,"age":6},{"id":10,"age":9},{"id":10,"age":2}] 

copyWithin

ES6 指定位置的成员复制到其他位置

//target(必需):从该位置开始替换数据。如果为负值,表示倒数。
//start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
//end(可选):到该位置前停止读取数据,默认等于数组长度。使用负数可从数组结尾处规定位置。
array.copyWithin(target, start = 0, end = this.length)

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]
var a=['OB1','Koro1','OB2','Koro2','OB3','Koro3','OB4','Koro4','OB5','Koro5']
// 2位置开始被替换,3位置开始读取要替换的 5位置前面停止替换
a.copyWithin(2,3,5)
// ["OB1","Koro1","Koro2","OB3","OB3","Koro3","OB4","Koro4","OB5","Koro5"] 

//第一个参数是开始被替换的元素位置
//要替换数据的位置范围:从第二个参数是开始读取的元素,在第三个参数前面一个元素停止读取
//数组的长度不会改变
//读了几个元素就从开始被替换的地方替换几个元素

fill

ES6: 填充数组 使用给定值,填充一个数组。

//第一个元素(必须): 要填充数组的值
//第二个元素(可选): 填充的开始位置,默认值为0
//第三个元素(可选):填充的结束位置,默认是为this.length

['a', 'b', 'c'].fill(7)
// [7, 7, 7]
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']

find findIndex

ES6 根据条件找到数组成员

find()定义:用于找出第一个符合条件的数组成员,并返回该成员,如果没有符合条件的成员,则返回undefined。

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

let new_array = arr.find(function(currentValue, index, arr), thisArg)
let new_array = arr.findIndex(function(currentValue, index, arr), thisArg)
//function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
//1. currentValue(必须),数组当前元素的值
//2. index(可选), 当前元素的索引值
//3. arr(可选),数组对象本身

// find
let a = [1, 4, -5, 10].find((n) => n < 0); // 返回元素-5
let b = [1, 4, -5, 10,NaN].find((n) => Object.is(NaN, n)); // 返回元素NaN
// findIndex
let a = [1, 4, -5, 10].findIndex((n) => n < 0); // 返回索引2
let b = [1, 4, -5, 10,NaN].findIndex((n) => Object.is(NaN, n)); // 返回索引4

filter

筛选出符合条件的新数组

let a = [1,2,3,4,5,6,7,8];
console.log(a.filter(e => e > 3));    // [4, 5, 6, 7, 8]
// or
console.log(a.filter(function(e){
    return e%2 == 0
}); // [2, 4, 6, 8]

forEach

迭代出数组中的每个元素

let a = [1,2,3,4,5];
let b = 0;
// function里可以有一个参数(就是迭代的数组中的元素)
a.forEach(item => {
    b = b + item;
});
console.log(b); // 15 ( 1+2+3+4+5 )

let a = [1,2,3,4,5];
// function里可以有最完整的3个参数
// 第一个:元素的值
// 第二个:该元素的索引(0开始)(可选)
// 第三个:数组本身(可选,用的较少)
a.forEach((item, index, arr) => {
    arr[index] = item * 10;
});
// or
a.forEach(function(item, idnex, arr){
    arr[index] = item * 10;
});
console.log(a); // [10,20,30,40,50]

concat

把两个数组合并

let a = [1,2,3,4,5];
let b = [6,7,8,9];

let c = a.concat(b);
let d = [...a, ...b]; //ES6 使用 ...

console.log(c); // [1,2,3,4,5,6,7,8,9]
console.log(d); // [1,2,3,4,5,6,7,8,9]

slice

取出数组的一部分作为新的数组

let a = [1,2,3,4,5,6,7,8];
let b = a.slice(2,4);
console.log(b); // [3, 4]

map

对数组中的每个元素进行处理,返回新的数组

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

// 回调函数的参数
//1. currentValue(必须),数组当前元素的值
//2. index(可选), 当前元素的索引值
//3. arr(可选),数组对象本身

let new_array = arr.map(function(currentValue, index, arr), thisArg)

let a = ['1','2','3','4'];
let result = a.map(function (value, index, array) {
return value + '新数组的新元素'
});
console.log(result, a); 
// ["1新数组的新元素","2新数组的新元素","3新数组的新元素","4新数组的新元素"] ["1","2","3","4"]

reduce, reduceRight

为数组提供累加器,合并为一个值

对累加器和数组中的每个元素(从左到右)应用一个函数,最终合并为一个值。

reduceRight和reduce的区别,只是reduceRight从右边开始累加

// 回调函数的参数
//1. total(必须),初始值, 或者上一次调用回调返回的值
//2. currentValue(必须),数组当前元素的值
//3. index(可选), 当前元素的索引值
//4. arr(可选),数组对象本身

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

 // 数组求和 
let sum = [0, 1, 2, 3].reduce(function (a, b) {
    return a + b;
}, 0);
// 6

// 将二维数组转化为一维 将数组元素展开
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
    (a, b) => a.concat(b), []
);
// [0, 1, 2, 3, 4, 5]

every

检测数组所有元素是否都符合函数定义的条件

// 回调函数的参数
//1. currentValue(必须),数组当前元素的值
//2. index(可选), 当前元素的索引值
//3. arr(可选),数组对象本身

array.every(function(currentValue, index, arr), thisValue)


function isBigEnough(element, index, array) { 
  return element >= 10; // 判断数组中的所有元素是否都大于10
}
let result = [12, 5, 8, 130, 44].every(isBigEnough);   // false
let result = [12, 54, 18, 130, 44].every(isBigEnough); // true
// 接受箭头函数写法 
[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true

some

数组中的是否有满足判断条件的元素

// 回调函数的参数
//1. currentValue(必须),数组当前元素的值
//2. index(可选), 当前元素的索引值
//3. arr(可选),数组对象本身

array.some(function(currentValue, index, arr), thisValue)

function isBigEnough(element, index, array) {
  return (element >= 10); //数组中是否有一个元素大于 10
}
let result = [2, 5, 8, 1, 4].some(isBigEnough); // false
let result = [12, 5, 8, 1, 4].some(isBigEnough); // true

inclues

ES7 返回一个布尔值,表示某个数组是否包含给定的值

includes方法是为了弥补indexOf方法的缺陷而出现的:

  1. indexOf方法不能识别NaN
  2. indexOf方法检查是否包含某个值不够语义化,需要判断是否不等于-1,表达不够直观
//searchElement(必须):被查找的元素
// fromIndex(可选):默认值为0,参数表示搜索的起始位置,接受负值。正值超过数组长度,数组不会被搜索,返回false。负值绝对值超过长数组度,重置从0开始搜索。

array.includes(searchElement,fromIndex=0)

let a=['OB','Koro1',1,NaN];
// let b=a.includes(NaN); // true 识别NaN
// let b=a.includes('Koro1',100); // false 超过数组长度 不搜索
// let b=a.includes('Koro1',-3);  // true 从倒数第三个元素开始搜索 
// let b=a.includes('Koro1',-100);  // true 负值绝对值超过数组长度,搜索整个数组

keys values entries

三个方法都返回一个新的 Array Iterator 对象,对象根据方法不同包含不同的值。

et a = ['a','b','c','d','e'];
let b = a.keys(); 

for (let key of b) {
    console.log(key); // 連續出現 1、2、3、4、5
}

 

 

admin

这个人很懒,什么都没留下

文章评论

  • uncekly

    Ioymzi Vacaciones De Propecia buy cialis non prescription Phxbko se vende cialis sin receta Dure Plus Longtemps There was no distinct difference in immunoreactivity and cellular distribution between potent and impotent patients. Fpeadi buy cialis Zorxvd

    2022-05-10
  • 您需要 登录 之后才可以评论