目录
一、es5中数组对象的方法
1.concat()
合并数组,并返回之后的数据
var a = [1, 2, 3];
var b = [4, 5, 6];
var c = a.concat(b);
console.log(c)
//打印:[1,2,3,4,5,6]
2.pop()
删除最后一位,并返回删除的数据
var a = [1, 2, 3, 4, 5];
var b = a.pop();
console.log(a,b);
//打印:[1,2,3,4] 5
3.shift()/unshift()
shift:删除第一位,并返回删除的数据
var a = [1, 2, 3, 4, 5];
var b = a.shift();
console.log(a,b);
//打印:[2,3,4,5] 1
unshift:在第一位新增数据,返回长度
var a = [1, 2, 3, 4, 5];
var b = a.unshift(6);
console.log(a,b);
//打印:[6,1,2,3,4,5] 6
4.push()
在最后一位新增数据,返回长度
var a = [1, 2, 3, 4];
var c = a.push('6');
console.log(c)
//打印:5
5.reverse()
反转数组,并返回
var a = [1,2,3];
console.log(a.reverse());
//打印:[3,2,1]
6.slice/splice()
slice:截取指定位置的数组并返回(如果slice方法的参数是负数,则表示倒数计算的位置(最后一位为-1))
var a = ['a', 'b', 'c'];
a.slice(0) // ["a", "b", "c"]
a.slice(1) // ["b", "c"]
a.slice(1, 2) // ["b"]
a.slice(2, 6) // ["c"]
a.slice() // ["a", "b", "c"]
splice:删除指定位置,并替换,返回删除的数据
var a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.splice(4, 2, 1, 2) // ["e", "f"]
a // ["a", "b", "c", "d", 1, 2]
二、es6中的数组对象的方法
1.indexOf()
查询并返回数据的索引
let arr = ['RJY', 'rjy', 'Rjy'];
var a=arr.indexOf('RJY');
console.log(a)
//打印:0
2.forEach
遍历数组全部元素(没有返回值),利用回调函数对数组进行操作,自动遍历数组.length次数,且无法break中途跳出循环,不支持return操作输出,return只用于控制循环是否跳出当前循环(难用于操作新值)
var arr = [1,2,3,4,5,6]
arr.forEach(function(e,index,array){
array[index]= e + 1
})
console.log(arr);
//打印[2, 3, 4, 5, 6, 7]
3.find()
查找数组中符合条件的元素,若有多个符合条件的元素,则返回第一个元素。
let a = [1, 2, 3, 4, 5];
a.find(function matcher(p){
return p == "2";
});
//打印: 2
4.findIndex()
查找数组中符合条件的元素索引,若有多个符合条件的元素,则返回第一个元素索引。若找不到就返回-1。
var a=[1,2,10,15]
var b=a.findIndex(function(value,index,array) {
return value > 9;
})
console.log(b)
//打印:2
5.fill()
将一定范围索引的数组元素内容填充为单个指定的值。
let a = new Array(5).fill(0);
console.log(a);
//打印:[0,0,0,0,0]
6.entrys()
遍历键值对。
for(let [key, value] of ['a', 'b'].entries()){
console.log(key, value);
}
//打印:
//0 a
//1 b
7.keys()
遍历键名。
for(let key of ['a', 'b'].keys()){
console.log(key);
}
//打印
// 0
// 1
8.values()
遍历键值。
for(let value of ['a', 'b'].values()){
console.log(value);
}
//打印
// "a"
// "b"
9.includes()
数组是否包含指定值。注意:与 Set 和 Map 的 has 方法区分;Set 的 has 方法用于查找值;Map 的 has 方法用于查找键名。
[1, 2, 3].includes(1);
//打印
// true
10.flat()
嵌套数组转一维数组。降维。
console.log([1 ,[2, 3]].flat());
//打印
// [1, 2, 3]