js內置對象Array練習

 /**
         *  JavaScript 內置對象 -->Array 數組篇
         *  
         */
          // isArray 判斷值是不是數組
          var temp=["1",2,3,4];
          document.write(Array.isArray(temp)+"<br/>");
    
          // join  方法設置分隔符將數組返回字符串
          document.write(temp.join("-")+"<br/>");
          
          // push 在數組的末尾添加一項  , pop 在數組的末尾移除一個元素
          temp.push("張三");
          document.write(temp+"<br/>");
          temp.pop();  
          document.write(temp+"<br/>");
          
          // shift 從前面開始移除數組
          temp.shift();
          document.write(temp+"<br/>");
          
          //unshift 在數組前面添加數組
          temp.unshift("4");
          document.write(temp+"<br/>");
          
          // reverse() 相反排序    sort()升序
          temp.reverse();
          document.write(temp+"<br/>");
          temp.sort();
          document.write(temp+"<br/>");
          
          // 通過比較函數 重新進行排序
          function compare(value1,value2){
              if(value1<value2){
                  return 1;
              }else if(value1>value2){
                  return -1;
              }else{
                  return 0;
              }
          }
          temp.sort(compare);
          document.write(temp+"<br/>");
          
          // concat 方法  :創建一個數組副本,將在當前數組中插入數據,並返回另一個副本, 
          var arr=["zhangsan","lisi"];
          var arr1=arr.concat("wangwu");
          document.write(arr+"<br/>");  //這個值並沒有改變
          document.write(arr1+"<br/>");
          
          // splice   通過指定參數進行對數組的添加、修改、刪除
          temp=[1,2,3,4];
          temp.splice(1,2);  //刪除數組  從 1座標開始刪   刪除兩個座標的元素  
          document.write(temp+"<br/>");   
          temp=[1,2,3,4];
          temp.splice(0,2,5,6); //從第0座標開始 插入 2個元素   可以用來做修改
          document.write(temp+"<br/>");
          temp.splice(4,2,7,8);   //從第四個座標開始插入兩個元素
          document.write(temp+"<br/>");
           
          //indexof 和  lastIndexOf  
          document.write(temp.indexOf(7)+"<br/>");
          document.write(temp.lastIndexOf(7)+"<br/>");  
發佈了28 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章