美文网首页
js数组方法

js数组方法

作者: 琳媚儿 | 来源:发表于2020-03-10 14:42 被阅读0次
     indexOf
    
    数组可以通过indexOf()来搜索一个指定的元素的位置,如未找到返回 -1;
    var arr = [10,20,"30","abc"];
    console.log(arr.indexOf(10)); //元素10的索引为0
    
    
    concat
    
    concat()方法把当前的  数组  和  另一个  数组连接起来,并返回一个新的  数组;
    var arr1 = ["a","b","c"];
    var arr2 = [1,2,3];
    var newArr = arr1.concat(arr2,"再次添加");
    newArr; //["a","b","c",1,2,3,"再次添加"];
    
    
     push和pop
    
    push()向数组的末尾添加若干元素,pop()  则把  数组的最后一个元素删除掉
    var arr = [1,2];
    arr.push("a","b");
    console.log(arr);//[1,2,"a","b"]
    
    arr.pop(); //pop() 返回“b”;
    arr; //打印[1,2,"a"]
    
    
    
    unshift和shift
    
    unshift()  向数组前面添加若干元素,shift()  则把数组的第一个元素删除掉
    var arr = [1,2];
    arr.unshift("a","b"); //返回新长度 4
    arr;//打印["a","b",1,2]
    arr.shift();//返回"a"
    arr; //打印["b",1,2]
    
    
    
    slice
    
    slice()  截取数组的部分元素,然后返回一个新的数组
    var arr = ["a","b","c","d","e","f","g"];
    console.log(arr.slice(0,3)); //从索引0开始,到索引3结束,但不包括3:["a","b","c"]
    console.log(arr.slice(3));  //从索引3开始到结束:"d","e","f","g"
    
    
    join
    
    join()  方法把数组的每个元素用指定的字符串连接起来,然后新的字符串
    
    var arr = ["a","b","c",1,2,3]; arr.join("-");  //"a-b-c-1-2-3"
    
    
    splice
    splice() 方法是修改数组的“万能方法”,他可以从指定的索引开始删除若干元素,然后再从该位置添加若干元素;
    var arr = ["苹果","橘子","香蕉","芋头","桂圆","山楂"];
    
    //从索引2开始删除3个元素,然后再添加两个元素
    arr.splice(2,3,"白梨","西瓜");
    console.log(arr); // "苹果","橘子","白梨","西瓜","山楂"
    
    
    

    相关文章

      网友评论

          本文标题:js数组方法

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