當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript Array join()用法及代碼示例

JavaScript join() 方法

join() 方法用於將數組的元素連接成一個字符串。它用一個數組調用並返回一個包含數組元素的字符串。

用法:

    array.join([separator]);

參數: separator它是一個可選參數,用於指定數組元素之間的分隔符,默認值為逗號。

返回值:包含數組元素的字符串

例:

    Input:
    var arr = [10, 20, 30, 40, 50];

    Function call:
    var str = arr.join();    

    Output:
    str = "10,20,30,40,50"

使用 Array.join() 方法將數組元素連接成字符串的 JavaScript 代碼

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var arr1 = ["Manju", "Amit", "Abhi", "Radib"];
		var arr2 = [10, 20, 30, 40, 50];
		var arr3 = [-10, -20, 0, 10, 20];
		
		var str1 = arr1.join();
		var str2 = arr2.join();
		var str3 = arr3.join();
		
		document.write("str1:" + str1 + "<br>");
		document.write("str2:" + str2 + "<br>");
		document.write("str3:" + str3 + "<br>");
		
		document.write("printing the types of the objects...<br>");
		document.write("type of arr1:" + typeof(arr1) + "<br>");
		document.write("type of arr2:" + typeof(arr2) + "<br>");
		document.write("type of arr3:" + typeof(arr3) + "<br>");
		document.write("type of str1:" + typeof(str1) + "<br>");
		document.write("type of str2:" + typeof(str2) + "<br>");
		document.write("type of str3:" + typeof(str3) + "<br>");
	</script>
</body>
</html>

輸出

str1:Manju,Amit,Abhi,Radib
str2:10,20,30,40,50
str3:-10,-20,0,10,20
printing the types of the objects...
type of arr1:object
type of arr2:object
type of arr3:object
type of str1:string
type of str2:string
type of str3:string



相關用法


注:本文由純淨天空篩選整理自 Array join() method with example in JavaScript。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。