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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语