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

举例讲解JavaScript中将数组元素转换为字符串的方法

程序员文章站 2023-01-01 20:15:15
首先来看一下从一个数组中选择元素的方法slice(): 源代码:

首先来看一下从一个数组中选择元素的方法slice():
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to extract the second and the third elements from the array.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var fruits = ["banana", "orange", "lemon", "apple", "mango"];
var citrus = fruits.slice(1,3);
var x=document.getelementbyid("demo");
x.innerhtml=citrus;
}
</script>
​
</body>
</html>   

测试结果:

orange,lemon

我们可以用数组的元素组成字符串,相关的join()方法使用例子:

源代码:

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

测试结果:

banana,orange,apple,mango

直接转换数组到字符串则可以用tostring()方法:
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">点击按钮将数组转为字符串并返回。</p>
​
<button onclick="myfunction()">点我</button>
​
<script>
function myfunction()
{
 var fruits = ["banana", "orange", "apple", "mango"];
 var str = fruits.tostring();
 var x=document.getelementbyid("demo");
 x.innerhtml= str;
}
</script>
​
</body>
</html>

测试结果:

banana,orange,apple,mango