美文网首页
javascript数组操作汇总

javascript数组操作汇总

作者: 爱酒爱剑爱江湖 | 来源:发表于2017-02-20 16:47 被阅读0次

    var colors = new Array('red','blue','black');

    //检测是否是数组
    if(colors instanceof Array){}
    if(Arrays.isArray(colors)){//es5新增}

    //查找数组项
    indexOf()
    lastIndexOf()
    //排序
    sort(); 可传递function作为排序规则
    reverse();

    //数组操作
    //pop push 数组模拟栈操作(FILO)
    var item = colors.pop();//'black'
    colors.length;//2
    var count = colors.push('black');//3
    colors.toString()//'red,blue,black'
    //shift unshift 数组模拟队列(FIFO)
    var item = colors.shift();//'red'
    colors.toString();//'blue,black'
    var count = colors.unshift('red');//3
    colors.toString()//'red,blue,black'

    slice(start,end);截取出新的数组,start不能为空。不会改变原数组
    var item = colors.slice(1);//["blue", "black"]
    var item = colors.slice(0,1);//["red"]

    splice()
    删除操作 传递2个参数,返回删除项组成的数组 colors.splice(0,1);//["red"]
    插入 colors.splice(1,0,'yellow','white')//"red,yellow,white,blue,black"
    //1表示起始位置,0表示要删除的项数 无返回值
    替换 colors.splice(1,1,'yellow','white')//"red,yellow,white,black"
    //返回被替换掉的项的数组
    迭代方法
    //每一项都返回true则返回true
    colors.every(function(item,index,array){return item=='blue'});
    //有一项都返回true则返回true
    colors.some(function(item,index,array){return item=='blue'});
    // 返回符合条件项的数组
    colors.filter(function(item,index,array){return item=='blue'})
    // 返回每项结果组成的数组
    colors.map(function(item,index,array){return item+='blue'})
    //执行操作
    colors.forEach(function(item,index,array){})

    相关文章

      网友评论

          本文标题:javascript数组操作汇总

          本文链接:https://www.haomeiwen.com/subject/grxqwttx.html