您的位置:首页 > 其它

Array 重排序方法和操作方法的简单实例

2014-01-24 09:39 656 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head>    <title>重排序方法和操作方法</title>    <script type="text/javascript">        //排序方法      function basicSort(){         var values=[0,10,2,3,12,5];         alert(values.reverse());//reverse()方法只是把数组的顺序反过来         alert(values.sort());//sort()方法比较的是字符串,大多数情况不是最佳的方案         alert(values.sort(compare));//sort()方法可以接收一个比较函数作为参数      }      //自定义比较函数,返回的数组是升序,也可以通过改变代码,如 value1<value2 return 1等来达到结果是降序的。      function compare(value1,value2){        if(value1 < value2){          return -1;        }else if(value1 > value2){         return 1;        }else{          return 0;        }      }      //操作方法 concat()方法是基于当前的数组中的所有项创建一个新数组      function basicConcat(){        var colors=["red","blue","pink"];        var colors2=colors.concat("yellow",["black","brown"]);//red,blue,pink,yellow,black,brown        alert(colors2);      }      //方法是基于当前的数组中的所有项创建一个新数组,可以接收一个或者两个参数,即截取  end > str >=start(即不包括结束位置的项)      function basicSlice(){         var colors=["red","blue","pink","yello","white"];         var colors2=colors.slice(1);         var colors3=colors.slice(1,4);         alert(colors2);         alert(colors3);      }      function basicSplice(){         var colors=["red","blue","pink","yello","white"];         var removed=colors.splice(0,2);//表删除 即删除前两项         alert("删除的项:"+removed+"----现在的项:"+colors)         var inserted=colors.splice(1,0,"black","gray");//表示在位置1处删除0项,插入新加项         alert("现在的项:"+colors);      }    </script></head><body>  <input type="button" value="排序Sort" onclick="basicSort();" />  <input type="button" value="concat" onclick="basicConcat();" />  <input type="button" value="slice" onclick="basicSlice();" />  <input type="button" value="splice" onclick="basicSplice();" /></body></html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Array 排序