目录
一、数组的方法整理(自用)
1.push
从尾部“推入”(添加)元素;返回新增后数组的长度;会改变原数组;
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.push(4,"four")); // 结果:8
console.log(arr); // 结果:[ 1, 'one', 2, 'two', 3, 'three', 4, 'four' ]
2.pop
从尾部“弹走”(删除)一个元素;返回被删除的元素;会改变原数组
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.pop()); // 结果:three
console.log(arr); // 结果:[ 1, 'one', 2, 'two', 3 ]
3.unshift
从头部插入(添加)元素;返回新增后数组的长度;会改变原数组
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.unshift(0,"zero")); // 结果:8
console.log(arr); // 结果:[ 0, 'zero', 1, 'one', 2, 'two', 3, 'three' ]
4.shift
从头部删除一个元素;返回被删除的元素;会改变原数组
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.shift()); // 结果:1
console.log(arr); // 结果:[ 'one', 2, 'two', 3, 'three' ]
5.splice(index,howmany,item)
对数组进行增删改;返回要改变的元素;会改变原数组
从索引为inde的位置,删除howmany个元素,元素item替换删除的部分,item可加可不加,也可以加多个
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.splice(2,0,4)); //增 结果: []
console.log(arr); // 结果: [ 1, 'one', 4, 2, 'two', 3, 'three' ]
console.log(arr.splice(2,3)); //删 结果:[ 4, 2, 'two' ]
console.log(arr); // 结果:[ 1, 'one', 3, 'three' ]
console.log(arr.splice(2,2,2,"two")) //改 结果:[3, 'three']
console.log(arr); // 结果:[ 1, 'one', 2, 'two' ]
6.join
用指定的分隔符(默认逗号作为分隔符)将数组的所有元素拼接成一个字符串;返回字符串;不会改变原数组
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.join()); // 结果:1,one,2,two,3,three
console.log(arr); // 结果:[ 1, 'one', 2, 'two', 3, 'three' ]
console.log(arr.join('$')); // 结果:1$one$2$two$3$three
7.sort
对数组的元素进行排序(默认是从小到大来排序 并且是根据字符串来排序的);返回排序后的新数组;会改变原数组
let arr=[1,"one",2,"two",3,"three",21,4,16];
console.log(arr.sort()); // 结果:[ 1, 16, 2, 21, 3, 4, 'one', 'three', 'two' ]
console.log(arr.sort((a,b)=>a-b)); //升序 结果:[ 1, 2, 3, 4, 16, 21, 'one', 'three', 'two' ]
console.log(arr.sort((a,b)=>b-a)); //降序 结果:[ 21, 16, 4, 3, 2, 1, 'one', 'three', 'two' ]
console.log(arr); // 结果:[ 21, 16, 4, 3, 2, 1, 'one', 'three', 'two' ]
8.slice(startIndex,endIndex)
切去索引startIndex到索引endIndex的数组,不包含索引endIndex的值;返回值是切出来的数组;不会改变原数组
let arr=[1,"one",2,"two",3,"three"]
console.log(arr.slice(1,3)); // 结果:[ 'one', 2 ]
console.log(arr); // 结果:[ 1, 'one', 2, 'two', 3, 'three' ]
9.map(callback)
映射数组(遍历数组) callback的参数:value-当前索引的值,index-索引,array-原数组;
返回新数组,包含为原始数组中的每个元素调用提供的函数的结果;不会改变原数组
let arr=[1,"one",2,"two",3,"three"]
arr2 = arr.map((value,index,arr)=>{
return value+2;
})
console.log(arr2); // 结果:[ 3, 'one2', 4, 'two2', 5, 'three2' ]
console.log(arr); // 结果:[ 1, 'one', 2, 'two', 3, 'three' ]
10.filter(callback)
过滤数组(遍历数组) callback的参数:value-当前索引的值,index-索引;
返回一个满足要求的新数组;不会改变原数组
let arr=[1,"one",2,"two",3,"three"]
let arr2 = arr.filter((value,index)=>{
return isNaN(value);
})
console.log(arr2); // 结果:[ 'one', 'two', 'three' ]
console.log(arr); // 结果:[ 1, 'one', 2, 'two', 3, 'three' ]