Mr. Lei

Js-数组API常用方法
转字符串 //方法一 String(arr); //方法二-join array.join("自定义连接符"...
扫描右侧二维码阅读全文
23
2019/04

Js-数组API常用方法

转字符串

//方法一
String(arr);

//方法二-join
array.join("自定义连接符");

//无缝拼接成字符串-join
var arr=[1,2,5,9,6];
arr.join("");//12596

//无缝拼接判断是否空数组-join
array.join("")=="";

concat拼接

var arr=[1,2,5,9,3,7,6];
arr.concat("值1","值2","值3");//arr=[1,2,5,9,3,7,6,"值1","值2","值3"]

slice选取

var arr=[1,2,5,9,3,7,6];
//        起始,结束+1
array.slice(1 ,3+1 );//2,5,9

splice插入/替换/删除

var arr=[1,2,5,9,3,7,6];
//插入    位置   值1 值2
arr.splice(1,0,11,22);//arr=[1,11,22,2,5,9,3,7,6]

//替换    起始 结束 值1 值2 ...
arr.splice(1 , 1 , 11, 22);//arr=[1,11,22,5,9,3,7,6]

//删除    起始 结束
arr.splice(0 , 2);//arr=[5,9,3,7,6]

排序

var arr=[1,2,5,9,3,7,6];
//字符串升序排序
arr.sort();//[1,2,3,5,6,7,9]

//自定义比较器-升序 排序
arr.sort(function (a,b){return a-b});//[1,2,3,5,6,7,9]

//自定义比较器-降序 排序
arr.sort(function (a,b){return -(a-b)});//[9,7,6,5,3,2,1]

//排序翻转(排序颠倒)
arr.reverse();

出栈/入栈

var arr=[1,2,5,9,3,7,6];
//头出栈
arr.shift();//arr=[2,5,9,3,7,6]

//头入栈
arr.unshift(0);//arr=[0,1,2,5,9,3,7,6]

//尾出栈
arr.pop();//arr=[1,2,5,9,3,7]

//尾入栈
array.push(0);//arr=[1,2,5,9,3,7,6,0]
Last modification:May 24th, 2019 at 12:22 pm

Leave a Comment