当前位置:网站首页>JS数组的方法大全
JS数组的方法大全
2022-07-28 05:19:00 【哈哈ha~】
一、常用的数组方法
- concat() 连接两个或更多的数组 返回新数组 不改变原数组
var a = [1,2,3]
var b = [4,5]
var c = a.concat(b)
console.log(a) // [1,2,3]
console.log(b) // [4,5]
console.log(c) // [1,2,3,4,5] - join() 把数组的所有元素放入一个字符串 元素通过指定的分隔符进行分隔 不改变原数组
//不传参数默认是, 传参 把数组中每一个元素toString()然后拼接
var a = [1,2,3]
var b = a.join('*')
console.log(a) // [1,2,3]
console.log(b) // 1*2*3- pop() 删除并返回数组的最后一个元素 改变原数组
var a = [1,2,3]
var b = a.pop()
console.log(a) // [1,2]
console.log(b) // 3- push() 向数组的末尾添加一个或更多元素 返回新的长度 改变原数组
var a = [1,2,3]
var b = a.push(4)
console.log(a) // [1,2,3,4]
console.log(b) // 4- shift() 删除并返回数组的第一个元素 改变原数组
var a = [1,2,3]
var b = a.shift()
console.log(a) // [2,3]
console.log(b) // 1- unshift() 向数组的开头添加一个或更多元素 返回新的长度 改变原数组
var a = [2,3]
var b = a.unshift(1)
console.log(a) // [1,2,3]
console.log(b) // 3- reverse() 颠倒数组中元素的顺序 返回颠倒后的数组 会改变原数组
var a = [1,2,3]
var b=a.reverse()
console.log(a) // [3,2,1]
console.log(b) // [3,2,1]
- sort() 对数组的元素进行排序 (按ASCII码) 返回排序后的数组 改变原数组
var a = ['a','b','d','c']
var b=a.sort()
console.log(a) // ['a','b','c','d']
console.log(b) // ['a','b','c','d']- slice() 从某个已有的数组返回选定的元素 返回新数组 不改变原数组
//slice(start,end) 返回[start,end)之间的元素组成的数组
var a = [1,2,3]
var b = a.slice(0,1)
var c = a.slice() // 不填参数默认剪切整个数组
console.log(a) // [1,2,3]
console.log(b) // [1]
console.log(c) // [1,2,3]
console.log(a===c) // false
// 负数表示从后往前数
var d = a.slice(-1,-2)
console.log(d) // [] 从左向右截取,所以为[]
var e = a.slice(-1)
console.log(e) // [3]- splice() 对数组进行删除修改 返回被删除的元素组成的数组 改变原数组
//splice(index,length,n1,n2....,nn) 表示从index开始删除length个元素,并从index开始新增元素n1~nn,放回被删除的元素组成的数组
var a = [1,2,3]
var b = a.splice(1,2,2,[3,4],5)
console.log(a) // [1,2,[3,4],5]
console.log(b) // [2,3]- toString() 把数组转换为字符串,并返回结果
var a=[1,2,3]
var b=a.toString()
console.log(b) //1,2,3- toLocaleString() 把数组转换为本地字符串 并返回结果
var a=[1,2,3]
var b=a.toLocaleString()
console.log(b) //1,2,3- valueOf() 返回数组对象的原始值
var a=[1,2,3]
var b=arr.valueOf()
console.log(b) //[1, 2, 3]二、ES5新增的数组方法
- indexOf() 查找某元素在数组中的位置 存在则返回第一个位置的下标 否则返回-1
var a = [1,2,3]
var b = a.indexOf(1)
var c = a.indexOf(3,3) //第二个参数表示从哪个位置开始查找某元素
console.log(b) // 0
console.log(c) // -1- lastIndexOf 和indexOf()相似 区别在于从尾部向首部查询 不改变原数组
var a = [1,2,3]
var b = a.lastIndexOf(1)
console.log(b) // 2
注:若不使用下标,则一般通过includes()方法代替indexOf()
- filter() 返回数组中满足条件的元素组成的新数组 原数组不变 filter()的参数是一个方法
var a = [1,2,3]
//第一个参数为一个函数 有三个参数 current:当前值 index:当前值下标 array:这个数组对象
var b = a.filter(function(current,index,array){
return current < 2
})
console.log(a) // [1,2,3]
console.log(b) // [1]- forEach() 遍历数组 为每个元素调用指定函数
var a = [1,2,3]
var b = a.forEach(function(el,index,arr){
console.log(el,index,arr)
})
/*1 0 (3) [1, 2, 3]
2 1 (3) [1, 2, 3]
3 2 (3) [1, 2, 3]
*/- map() 调用的数组的每一个元素传递给指定的函数 返回一个新数组 不改变原数组
var a = [1,2,3];
var b = a.map(function(el){
return el*el;
});
console.log(b); // [1,4,9]- every() 判断数组中每一项都是否满足条件 只有所有项都满足条件 才会返回true
var a = [1,2,3];
var b = a.every(function(x){
return x>1;
});
console.log(b); // false- some() 判断数组中是否存在满足条件的项 只要有一项满足条件 就会返回true
var a = [1,2,3];
var b = a.some(function(x){
return x>1;
});
console.log(b); // true- reduce() 两个参数:函数和递归的初始值 从数组的第一项开始 逐个遍历到最后
//函数接收四个参数值:前一个值 当前值 索引 数组对象
var a=[1,2,3];
var b=a.reduce(function(a,b){
return a+b;
})
console.log(b)//7- reduceRight() 与reduce()使用一样 从数组的最后一项开始 向前遍历到第一项
三、ES6新增的数组方法
(一)数组创建
- Array.of():将参数中所有值作为元素形成数组
var re=Array.of(10) //1个元素 取出来是10
var rem=Array(10) //10个空元素 取出来是undefined
console.log(re,rem)
/* [10] (10)
0: 10 [empty × 10]
length: 1 length: 10
*/
var re=Array.of(10,20,30) //工厂创建
console.log(re) //[10, 20, 30]- Array.from():将类数组对象或可迭代对象转化为数组
// 参数为数组,返回与原数组一样的数组但不相等
console.log(Array.from([1, 2])); // [1, 2]
// 参数含空位
console.log(Array.from([1, , 3])); // [1, undefined, 3]
var arr=Array.from([1,2,3],function(el){
return el*2
})
console.log(arr) // [2,4,6]- 类数组对象:必须含有 length 属性,且元素属性名必须是数值或者可转换为数值的字符
var arr = Array.from({
0: ''hello,
1: 'world',
2: 2022,
length: 3
});
console.log(arr); // ['hello', 'world', 2022]
// 没有 length 属性,则返回空数组
var arr = Array.from({
0: ''hello,
1: 'world',
2: 2022,
});
console.log(arr); // []
// 元素属性名不为数值且无法转换为数值,返回长度为 length 元素值为 undefined 的数组
var arr = Array.from({
a: 1,
b: 2,
length: 2
});
console.log(arr); // [undefined, undefined](二)转换可迭代对象
- 转换map
var map = new Map();
map.set('key0', 'value0');
map.set('key1', 'value1');
console.log(Array.from(map)); // [['key0', 'value0'],['key1','value1']]- 转换set
var arr = [1, 2, 3];
var set = new Set(arr);
console.log(Array.from(set)); // [1, 2, 3]转换字符串
var str = 'abc';
console.log(Array.from(str)); // ["a", "b", "c"]二、扩展的方法
- find():查找数组中符合条件的元素,若有多个符合条件的元素,则返回第一个元素
var arr=[10,20,30]
var re= arr.find(function(el){
if(el>20){
return true
}
})
console.log(re) //30注:数组空位处理为 undefined
- findIndex():查找数组中符合条件的元素索引,有多个符合条件的元素时返回第一个元素索引
var arr=[10,20,30]
var re= arr.findIndex(function(el){
if(el>20){
return true
}
})
console.log(re) //2- includes():包含,数组是否包含指定值
var arr=[1,2,3,4,5]
var re=arr.includes(4)
console.log(re) //返回布尔值 truefill():填充,将一定范围索引的数组元素内容填充为单个指定的值
//改变原数组 无参数范围时全部填充
var arr=[1,2,3,4]
var re=arr.fill("hello")
console.log(re,arr)
//打印 0: "hello" 1: "hello" 2: "hello" 3: "hello" var arr=[{name:"hha",age:21},{name:"heie",age:28},{name:"xixi",age:14},{name:"oo",age:10}]
arr.map(function(el){
if(el.age>=18){
el.drink=true
}
})
console.log(arr)- flat(): 降维 嵌套数组转一维数组
var arr=[[10,20],30,40,[50,60,[70,[100,200],80],90]]
var arr2=arr.flat(2)
console.log(arr2)
/*
0: 10
1: 20
2: 30
3: 40
4: 50
5: 60
6: 70
7: (2) [100, 200]
8: 80
9: 90
*/案例:自己设计实现flat函数:(默认完全降维 count为降级级别)
Array.prototype.myflat=function(count=Infinity){
var arr=[]
for(i=0;i<this.length;i++){
if(this[i].constructor==Array&&count>0){
var newarr=this[i].myflat(count-1)
for(j=0;j<newarr.length;j++){
arr.push(newarr[j])
}
}else{
arr.push(this[i])
}
}
return arr
}
var re2=arr.myflat(2)
console.log(re2)
/*
0: 10
1: 20
2: 50
3: 60
4: 70
5: (2) [100, 200]
6: 80
*/遍历:
- entrys():遍历键值对
for(let [key, value] of ['a', 'b'].entries()){
console.log(key, value);
}
// 0 "a"
// 1 "b"
// 不使用 for... of 循环
let entries = ['a', 'b'].entries();
console.log(entries.next().value); // [0, "a"]
console.log(entries.next().value); // [1, "b"]
// 数组含空位
console.log([...[,'a'].entries()]); // [[0, undefined], [1, "a"]]- keys():遍历键名
for(let key of ['a', 'b'].keys()){
console.log(key);
}
// 0 1
// 数组含空位
console.log([...[,'a'].keys()]); // [0, 1]values():遍历键值
for(let value of ['a', 'b'].values()){
console.log(value);
}
// "a" "b"
// 数组含空位
console.log([...[,'a'].values()]); // [undefined, "a"]案例:
arr=[10,20,30]
var re=arr.keys()
for(let i of re){
console.log(i) //打印 0 1 2
}
console.log(re) //Array Iterator {}
var ree=arr.values()
for(let i of ree){
console.log(i) //打印 10 20 30
}三、扩展运算符(...)
复制数组:
var arr = [1, 2],
arr1 = [...arr];
console.log(arr1); // [1, 2]
// 数组含空位
var arr2 = [1, , 3],
arr3 = [...arr2];
console.log(arr3); [1, undefined, 3]合并数组:
var arr = [10, 20, 30]
var arr1=[1,2,3]
var arr2 = [...arr,...arr1]
console.log(arr, arr2)总结:
原数组改变的方法:push pop shift unshift reverse sort splice
不改变原数组的方法:concat map filter join every some indexOf slice forEach
边栏推荐
猜你喜欢

Delete specific elements in order table OJ

SVG了解与绘图应用

Review of metallurgical physical chemistry -- Fundamentals of chemical reaction kinetics

ECCV22 最新54篇论文主图整理

Example of main diagram of paper model

How to compare long and integer and why to report errors
![[idea plug-in artifact] teaches you how to set all attributes in an entity class with one click of idea](/img/d6/4e69480c5ad5040ee48941ca0fcb37.png)
[idea plug-in artifact] teaches you how to set all attributes in an entity class with one click of idea

Advanced multithreading: the role and implementation principle of volatile

蒙特卡罗方法求解圆周率π并用turtle画点,以及完成进度条问题

Idea configures the service (run dashboard) service, and multiple modules are started at the same time
随机推荐
Thesis writing function words
Idea configures the service (run dashboard) service, and multiple modules are started at the same time
顺序表oj题目
顺序表的增删查改
Image enhancement - msrcr
wangeditor(@4.7.15)-轻量级的富文本编辑器
openjudge:万年历
冶金物理化学复习 --- 复杂反应的速率方程
排序之插入排序
Mutual conversion between latex and word
Mabtis (I) basic use of framework
标准C语言学习总结3
Oracle view lock table statement and unlocking method
Oracle uses SQL to query the field information of a table (field type, length, etc.)
latex和word之间相互转换
C语言回顾(可变参数篇)
Sequence table OJ topic
Openjudge: maximum span of string
MySQL adds sequence number to query results
URL 形式