当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 举例讲解JavaScript中将数组元素转换为字符串的方法

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

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

首先来看一下从一个数组中选择元素的方法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 

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

相关文章:

验证码:
移动技术网