//检测数组
if (value instanceof Array) {
//do something
}
if (Array.isArray(value)) {
//do something
}
//数组转换为string
var colors = ["red", "green", "blue"];
alert(colors.toString()); //red,green,blue
alert(colors.jion("||")); //red||green||blue
//栈方法
var colors = new Array();
var count = colors.push("green", "red");
alert(count); //2
count = colors.push("blue");
alert(count); //3
var item = colors.pop();
alert(item); //blue
alert(colors.length); //2
//队列方法
var colors = new Array();
var count = colors.push("green", "red");
alert(count); //2
count = colors.push("blue");
alert(count); //3
var item = colors.shift();
alert(item); //green
alert(colors.length); //2
//重排序方法
var values = [1, 2, 3, 4, 5];
values.reverse();
alert(values); //5,4,3,2,1
var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); //15, 10, 5, 1, 0
function compare(value1, value2) {
if (value1 < value2) {
return 1;
} else if (value1 > value2) {
return -1;
} else {
return 0;
}
}
//拼接
var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow");
alert(colors); //red,green,blue
alert(colors2); //red,green,blue,yellow
//截取
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
alert(colors2); //green,blue,yellow,purple
var colors3 = colors.slice(1, 4);
alert(colors3); //green,blue,yellow
//删除
var colors = ["red", "green", "blue"];
var removed = colors.splice(0, 1);
alert(colors); //green,blue
alert(removed); //red
removed = colors.splice(1, 0, "yellow", "orange");
alert(colors); //green,yellow,orange,blue
alert(removed); //空数组
removed = colors.splice(1, 1, "red", "purple");
alert(colors); //green,red,purple,orange,blue
alert(removed); //yellow
//位置方法
var numbers = [1, 2, 3, 4, 5];
alert(numbers.indexOf(4)); // 3,从前向后查找
alert(numbers.lastIndexOf(4)); //3,从后向前查找
Javascript中Array类型操作
最新推荐文章于 2024-08-17 12:54:01 发布