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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章