zoukankan      html  css  js  c++  java
  • JavaScript数组:增删改查、排序等

    直接上代码

    // 数组应用
        var peoples = ["Jack","Tom","William","Tod","Cart","Jhson"];
        console.log('原始:'+'length('+ peoples.length +')==' + peoples);
        // push(元素),从尾部添加
        peoples.push("Smith","Wolf");
        console.log('push:'+'length('+ peoples.length +')==' + peoples);
        // unshift(元素),从头部添加
        peoples.unshift("Anderson");
        console.log('unshift:'+'length('+ peoples.length +')==' + peoples);
        // pop(),从尾部删除
        peoples.pop();
        console.log('pop:'+'length('+ peoples.length +')==' + peoples);
        // shift(),从头部删除
        peoples.shift();
        console.log('shift:'+'length('+ peoples.length +')==' + peoples);
        // splice(开始,长度),删除
        peoples.splice(2,3);
        console.log('splice(2,3):'+'length('+ peoples.length +')==' + peoples);
        // splice(开始, 长度,元素…),先删除,后插入(当长度为0时,相当于插入;当长度等于元素个数时,相当于替换)
        peoples.splice(2,1,"AK-47","91","八一");
        console.log('splice(2,1,"AK-47","91","八一")'+'length('+ peoples.length +')==' + peoples);
        // concat(数组2)连接两个数组
        peoples.concat(["Mini","Coper"]);
        console.log('concat(["Mini","Coper"]):'+'length('+ peoples.length +')==' + peoples);
        // join(分隔符)用分隔符,组合数组元素,生成字符串,字符串split
        peoples.join('-=0=-');
        console.log("join('-=0=-'):"+'length('+ peoples.length +')==' + peoples);
    
        // sort([比较函数]),排序一个数组,
        // 注:排序一个字符串数组和数字数组不同
        peoples.sort();
        console.log("sort:"+'length('+ peoples.length +')==' + peoples);
        var numArr = [12,7,1212,11,318,33];
        numArr.sort();
        console.log("sort:"+'length('+ numArr.length +')==' + numArr);
        numArr.sort(function(n1,n2){
            /*
                if(n1 < n2){
                    return -1;
                }else if(n1 > n2){
                    return 1;
                }else{
                    return 0;
                }
            */
        //上面的代码简化如下:
    return n1 - n2; }); console.log("sort(function(...)):"+'length('+ numArr.length +')==' + numArr);

    链接:

    网易云课堂-关于数组讲解

  • 相关阅读:
    jquery 查找子元素的几种方法
    kvm虚拟化之kvm虚拟机控制台登陆
    KVM虚拟化之windows虚拟机性能调整
    KVM虚拟机的日常管理与配置
    windows kvm虚拟机安装
    linux kvm虚拟机安装
    如何在linux上安装使用virt-manager
    KVM虚拟环境安装
    SSH批量管理 expect自动交互
    LVS+keepalived快速搭建测试环境
  • 原文地址:https://www.cnblogs.com/On1Key/p/5843012.html
Copyright © 2011-2022 走看看