当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript中数组的合并以及排序实现示例

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

2019年08月01日  | 移动技术网IT编程  | 我要评论

合并两个数组 - 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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网