欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript中数组的合并以及排序实现示例

程序员文章站 2022-07-01 14:00:47
合并两个数组 - concat() 源代码: ​...

合并两个数组 - concat()
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">点击按钮合并数组。</p>
​
<button onclick="myfunction()">点我</button>
​
<script>
function myfunction()
{
var hege = ["cecilie", "lone"];
var stale = ["emil", "tobias", "linus"];
var children = hege.concat(stale);
var x=document.getelementbyid("demo");
x.innerhtml=children;
}
</script>
​
</body>
</html>

测试结果:

cecilie,lone,emil,tobias,linus


合并三个数组 - concat()
源代码:

<!doctype html>
<html>
<body>

<script>

var parents = ["jani", "tove"];
var brothers = ["stale", "kai jim", "borge"];
var children = ["cecilie", "lone"];
var family = parents.concat(brothers, children);
document.write(family);

</script>

</body>
</html>

测试结果:

jani,tove,stale,kai jim,borge,cecilie,lone


数组排序(按字母顺序升序)- sort()
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to sort the array.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var fruits = ["banana", "orange", "apple", "mango"];
fruits.sort();
var x=document.getelementbyid("demo");
x.innerhtml=fruits;
}
</script>
​
</body>
</html> 

测试结果:

apple,banana,mango,orange

数字排序(按数字顺序升序)- sort()
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to sort the array.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
var x=document.getelementbyid("demo");
x.innerhtml=points;
}
</script>
​
</body>
</html>  

测试结果:

1,5,10,25,40,100

数字排序(按数字顺序降序)- sort()
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to sort the array.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});
var x=document.getelementbyid("demo");
x.innerhtml=points;
}
</script>
​
</body>
</html>

测试结果:

100,40,25,10,5,1

将一个数组中的元素的顺序反转排序 - reverse()
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to reverse the order of the elements in the array.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
var fruits = ["banana", "orange", "apple", "mango"];
​
function myfunction()
{
fruits.reverse();
var x=document.getelementbyid("demo");
x.innerhtml=fruits;
}
</script>
​
</body>
</html>  

测试结果:

mango,apple,orange,banana