js 数组操作基本方法

时间:2022-09-15 23:50:11

js 数组创建

//创建数组的四种方式, 直接举例
var arr1 = new Array();
var arr2 = new Array(3); //这个地方需要特别声明, 即便是设置了3的长度, 并不是意味长度不能超过3, 是不是有点变变
var arr3 = new Array("a", "b", "c");
var arr4 = ["a", "b", "c"];

js 数组访问

//数组的基本操作:遍历
for(var i=0;i<arr3.length;i++){
alert(arr3[i]);
}

        toString():把数组转换成一个字符串 

var testarr = ["a","b","c"];
alert(testarr.toString());
var testarr2 = [1,2,3];
alert(testarr2.toString());


toLocaleString():把数组转换成一个字符串 

var testarr = ["a","b","c"];
alert(testarr.toLocaleString());
var testarr2 = ["甲","乙","丙"];
alert(testarr2.toLocaleString());


join():把数组转换成一个用符号连接的字符串 

var testarr = ["a","b","c"];
alert(testarr.join());


shift():将数组头部的一个元素移出 

var testarr = ["a","b","c"];
testarr.shift();
alert(testarr.join());


unshift():在数组的头部插入一个元素 

var testarr = ["a","b","c"];
testarr.unshift("e");
alert(testarr.join());


pop():从数组尾部删除一个元素 

var testarr = ["a","b","c"];
testarr.pop();
alert(testarr.join());


push():把元素添加到数组的尾部 

var testarr = ["a","b","c"];
testarr.push("e");
testarr.push("f","g");
testarr.push(["h","i"]);
alert(testarr.join());


concat():把元素添加到数组的尾部

var testarr = ["a","b","c"];
testarr = testarr.concat("e");
testarr = testarr.concat("f","g");
testarr = testarr.concat(["h","i"]);
alert(testarr.join());


【这个地方push, concat区别就是, push的元素是数组时候,是作为一个元素, 二concat是分解数组】

slice():返回数组的部分 

var testarr = ["a","b","c"];
var testarr2= testarr.slice(2);
alert(testarr2.join());
var teststr = "abc";
alert(teststr.slice(2));


reverse():将数组反向排序 

var testarr = ["a","b","c"];
testarr.reverse();
alert(testarr);


sort():对数组进行排序操作 

var testarr = ["a","b","c","1","e"];
testarr.sort();
alert(testarr);
function compare(value1, value2) {
if (value1 < value2) {
return 1;
} else if (value1 > value2) {
return -1;
} else {
return 0;
}
}
testarr.sort(compare);
alert(testarr);


splice():插入、删除或者替换一个数组元素 
    参数:arr.splice(index,howmany,element1,... ...,elementN);
         3、参数解释:
               1、index---------从该下标开始删除
               2、howmany----删除指定数量的元素
               3、elements-----插入的元素

var testarr = ["a","b","c","1","e"];
testarr.splice(3,0,"x");
testarr.splice(3,1,"x");
testarr.splice(3,2,"x","y");
alert(testarr);