JavaScript中实现数组的排序、乱序和搜索

所有这些功能,用一个sort()就可以完成了。

1. 排序:
默认的sort()按字符编码排序的:

<script type=”text/javascript”>
<!–
 var testArray=[3,324,5345,6546,134,5654,665];
 testArray.sort();
 alert(testArray);
//–>
</script>

现在要让它按照数值大小排序:

<script type=”text/javascript”>
<!–
 var testArray=[3,324,5345,6546,134,5654,665];
 testArray.sort(function(a,b){return a-b;});
 alert(testArray);
//–>
</script>

只要传递一个比较函数给sort就可以了,如果比较函数的值小于0,则表示a必须出现在b前面,否则在b后面。

2. 乱序:
让比较函数随机传回-1或1就可以了:

<script type=”text/javascript”>
<!–
 var testArray=[1,2,3,4,5,6,7,8,9,10,22,33,55,77,88,99];
 testArray.sort(function(){return Math.random()>0.5?-1:1;});
 alert(testArray);
//–>
</script>
 

3. 搜索:
用sort()来玩搜索还蛮新鲜的,呵呵,看看是怎么玩的吧。
我现在要把数组里含有字母’a’的元素全部找出来,如果没有sort(),似乎只能用遍历了,遍历的效率…那个叫恐怖啊!!具体做法如下:

<script type=”text/javascript”>
<!–
 var testArray=[‘df’, ‘rtr’, ‘wy’, ‘dafd’, ‘dfs’, ‘wefa’, ‘tyr’, ‘rty’, ‘rty’, ‘ryt’, ‘afds’, ‘wer’, ‘te’];
 testArray.sort(function(a,b){return a.indexOf(‘a’)==-1?1:-1;});
 alert(testArray);
//–>
</script>

这样就把数组中含有字母’a’的元素全部放到数组前面啦,再经过一些简单的处理,就可以输出搜索结果了。

以上是我总结的三种在javascript中用sort()操作数组的方法,如果你有兴趣,你会发现sort()还有好多妙用呢……

— EOF —

《JavaScript中实现数组的排序、乱序和搜索》有24个想法

  1. 竹胶板-竹木模板厂成立于1998年、苏浙皖三省交界处风景秀丽的太华镇。公司占地面积10000平方米,拥有固定资产近500万元。主要生产竹胶板系列产品,重点生产…

  2. 网络外包服务 企业官网建设 诚信通托管 诚信通店铺装修 网站制作 网站设计 阿里巴巴代运营 网站Seo优化 阿里巴巴托管 天猫托管 天猫店铺装修 网络推广 网站推广 网站…

  3. Howdy very cool blog!! Guy .. Beautiful .. Amazing .. I will bookmark your web site and take the feeds also¡KI’m satisfied to search out numerous useful information right here in the put up, we’d like develop extra strategies in this regard, thank you for sharing. . . . . .

  4. Thank you, I’ve just been looking for information about this subject for a while and yours is the best I’ve came upon so far. However, what about the bottom line? Are you positive in regards to the supply?

  5. It appears that the word is actually combination of couple of British slang words and it appears there is not yet official accepted of Hob Knocker.

  6. Sie durfte frohlocken, weil er stürmisch zurückküsste.Als Roger zurückkam, saugte sie reglerecht den frischen Duft auf, den er mitbrachte.

  7. Right here is the perfect web site for anyone who would like to understand this topic. You understand a whole lot its almost hard to argue with you (not that I really will need to…HaHa). You certainly put a fresh spin on a topic which has been written about for a long time. Wonderful stuff, just wonderful!|

  8. garcinia vibe and nutra cleanse dr. oz on forskolin 125 mg green coffee yorumlar acai vitamin benefits alo allure aloe vera and mangosteen and mango where to buy hoodia gordonii opinie pafal prop 65 psyllium health benefits of chitosan with glucomannan where to buy organic guar gum powder lipozene ingredient list glucomannan pills cvs

发表评论

电子邮件地址不会被公开。 必填项已用*标注