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);

    链接:

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

  • 相关阅读:
    常用命令-eval简析
    bash手册 之重定向原理与实现
    TCP/IP 编程
    SQL Server存储内幕系列
    ORACLE优化器RBO与CBO介绍总结
    24小时学通LINUX内核系列
    SQL Server 优化器+SQL 基础
    JAVA 强引用、软引用、弱引用、虚引用
    iOS 如何做才安全--逆向工程
    Python 基础学习
  • 原文地址:https://www.cnblogs.com/On1Key/p/5843012.html
Copyright © 2011-2022 走看看