Javascript中Array类型操作

//检测数组
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,从后向前查找

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值