数组常用方法有哪些?
2021-02-04 01:15
标签:使用 fun 参数 des sharp return break indexof 改变 ——数组中常用的方法有:给数组末尾添加新内容的push方法,删除数组最后一项的pop方法,删除数组第一项的shift方法,向数组首位添加新内容unshift方法等等 1、push() 向数组的末尾添加新内容 2、pop() 3、shift() 4、unshift() 5、slice() 按照条件查找出其中的部分内容 6、splice() 对数组进行增删改 返回空数组 修改: 删除: 7、join() 用指定的分隔符将数组每一项拼接为字符串 8、concat() 用于连接两个或多个数组 9、indexOf() 检测当前值在数组中第一次出现的位置索引 10、lastIndexOf() 检测当前值在数组中最后一次出现的位置索引 11、includes() 判断一个数组是否包含一个指定的值 12、sort() 对数组的元素进行排序(默认是从小到大来排序 并且是根据字符串来排序的) 13、reverse() 把数组倒过来排列 14、forEach() 循环遍历数组每一项 数组常用方法有哪些? 标签:使用 fun 参数 des sharp return break indexof 改变 原文地址:https://www.cnblogs.com/xsd1/p/12797594.html数组常用的一些方法
let ary1 = [12,34,26];
ary1.push(100); //返回一个新的长度
length=4console.log(ary1)//结果为 [12,34,26,100]
let ary2 = [108,112,39,10];
ary2.pop();//删除的最后一项为10
console.log(ary2);//[108, 112, 39]
let ary3 = [0,108,112,39];
ary3.shift();//删除的第一项为0
console.log(ary3);//[108, 112, 39]
let ary4 = [‘c‘,‘d‘];
ary4.unshift(‘a‘,‘b‘);
console.log(ary4);//["a", "b", "c", "d"]
let ary5 = [1,2,3,4,5,6,7,8,9];
//console.log(ary5.slice(2,8));//从索引2开始查找到索引为8的内容,结果为[3, 4, 5, 6, 7, 8]
//console.log(ary5.slice(0));
console.log(ary5.slice(-2,-1));//[8]
//增加
let ary6_z = [33,44,55,66,77,88];
ary6_z.splice(2,0,‘a‘,‘b‘)
console.log(ary6_z);// [33, 44, "a", "b", 55, 66, 77, 88]
//修改
let ary6_x = [33,44,55,66,77,88];
ary6_x.splice(1,2,‘x‘,‘y‘)
console.log(ary6_x);// [33, "x", "y", 66, 77, 88]
//删除
let ary6_s = [33,44,55,66,77,88];
//console.log(ary6.splice(3,2))//[66, 77]
console.log(ary6_s.splice(3));//[66, 77, 88]
let ary7 = [1,2,3];
console.log(ary7.join(‘、‘));//1、2、3
let ary8 = [‘你‘];
let ary80 = ary8.concat(‘好‘);
console.log(ary80);//["你", "好"]
let ary9 = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘a‘,‘f‘];
console.log(ary9.indexOf(‘c‘));//2
console.log(ary9.indexOf(‘a‘,3))//5
let ary10 = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘a‘,‘f‘];
console.log(ary10.lastIndexOf(‘c‘));//2
console.log(ary10.lastIndexOf(‘f‘,1))//-1
let ary13 = [‘a‘,‘b‘,‘c‘,‘d‘];
console.log(ary13.includes(‘c‘));//true
console.log(ary13.includes(2));//false
let ary11 = [32,44,23,54,90,12,9];
ary11.sort(function(a,b){ // return a-b; // 结果[9, 12, 23, 32, 44, 54, 90]
// return b-a; // 结果[90, 54, 44, 32, 23, 12, 9] })
console.log(ary11);
let ary12 = [6,8,10,12];
console.log(ary12.reverse());//[12, 10, 8, 6]
let ary14 = [‘a‘,‘b‘,‘c‘,‘d‘];
let item = ary14.forEach(function(item,index,ary){
console.log(item,index,ary);
})