JavaScript中数组的合并以及排序实现示例
合并两个数组-concat()
源代码:
<!DOCTYPEhtml> <html> <body> <pid="demo">点击按钮合并数组。</p> <buttononclick="myFunction()">点我</button> <script> functionmyFunction() { varhege=["Cecilie","Lone"]; varstale=["Emil","Tobias","Linus"]; varchildren=hege.concat(stale); varx=document.getElementById("demo"); x.innerHTML=children; } </script> </body> </html>
测试结果:
Cecilie,Lone,Emil,Tobias,Linus
合并三个数组-concat()
源代码:
<!DOCTYPEhtml> <html> <body> <script> varparents=["Jani","Tove"]; varbrothers=["Stale","KaiJim","Borge"]; varchildren=["Cecilie","Lone"]; varfamily=parents.concat(brothers,children); document.write(family); </script> </body> </html>
测试结果:
Jani,Tove,Stale,KaiJim,Borge,Cecilie,Lone
数组排序(按字母顺序升序)-sort()
源代码:
<!DOCTYPEhtml> <html> <body> <pid="demo">Clickthebuttontosortthearray.</p> <buttononclick="myFunction()">Tryit</button> <script> functionmyFunction() { varfruits=["Banana","Orange","Apple","Mango"]; fruits.sort(); varx=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
测试结果:
Apple,Banana,Mango,Orange
数字排序(按数字顺序升序)-sort()
源代码:
<!DOCTYPEhtml> <html> <body> <pid="demo">Clickthebuttontosortthearray.</p> <buttononclick="myFunction()">Tryit</button> <script> functionmyFunction() { varpoints=[40,100,1,5,25,10]; points.sort(function(a,b){returna-b}); varx=document.getElementById("demo"); x.innerHTML=points; } </script> </body> </html>
测试结果:
1,5,10,25,40,100
数字排序(按数字顺序降序)-sort()
源代码:
<!DOCTYPEhtml> <html> <body> <pid="demo">Clickthebuttontosortthearray.</p> <buttononclick="myFunction()">Tryit</button> <script> functionmyFunction() { varpoints=[40,100,1,5,25,10]; points.sort(function(a,b){returnb-a}); varx=document.getElementById("demo"); x.innerHTML=points; } </script> </body> </html>
测试结果:
100,40,25,10,5,1
将一个数组中的元素的顺序反转排序-reverse()
源代码:
<!DOCTYPEhtml> <html> <body> <pid="demo">Clickthebuttontoreversetheorderoftheelementsinthearray.</p> <buttononclick="myFunction()">Tryit</button> <script> varfruits=["Banana","Orange","Apple","Mango"]; functionmyFunction() { fruits.reverse(); varx=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
测试结果:
Mango,Apple,Orange,Banana