1)JavaScript toString()方法 (1) JavaScript toString() method)
toString() method is not only for the arrays, but it can be used other types of objects also, it is used to convert an object’s value to the string. The values are separated by the commas.
toString()方法不仅适用于数组,而且还可以用于其他类型的对象,它用于将对象的值转换为字符串。 这些值用逗号分隔。
Syntax:
句法:
object.toString();
2)JavaScript join()方法 (2) JavaScript join() method)
join() method is an array method and it can be used with the arrays. It is used to join the array elements and returns a string. The values are separated by the commas (by default), using join() method we can also specify the separator.
join()方法是一个数组方法,可以与数组一起使用。 它用于连接数组元素并返回一个字符串。 值之间用逗号分隔(默认情况下),使用join()方法,我们还可以指定分隔符。
Syntax:
句法:
array.join([separator]);
Here, separator is an optional parameter, which defines the separator between the array elements in the string.
在这里, 分隔符是一个可选参数,它定义了字符串中数组元素之间的分隔符。
Examples:
例子:
Input:
var arr = ["Manju", "Amit", "Abhi", "Radib"];
Function call Output
arr.toString() "Manju,Amit,Abhi,Radib"
arr.join() "Manju,Amit,Abhi,Radib"
arr.join(" ") "Manju Amit Abhi Radib"
JavaScript code to demonstrate example of toString() and join() methods
JavaScript代码演示toString()和join()方法的示例
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var arr1 = ["Manju", "Amit", "Abhi", "Radib"];
var arr2 = [10, 20, 30, 40, 50];
var str1 = arr1.toString();
var str2 = arr2.toString();
document.write("<br>using toString()...<br>");
document.write("str1: " + str1 + "<br>");
document.write("str2: " + str2 + "<br>");
var str3 = arr1.join();
var str4 = arr2.join();
document.write("<br>using join()...<br>");
document.write("str3: " + str3 + "<br>");
document.write("str4: " + str4 + "<br>");
var str5 = arr1.join(" ");
var str6 = arr2.join(" ");
document.write("<br>using join() with separator...<br>");
document.write("str5: " + str5 + "<br>");
document.write("str6: " + str6 + "<br>");
document.write("<br>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 str1: " + typeof(str1) + "<br>");
document.write("type of str2: " + typeof(str2) + "<br>");
document.write("type of str3: " + typeof(str3) + "<br>");
document.write("type of str4: " + typeof(str4) + "<br>");
document.write("type of str5: " + typeof(str5) + "<br>");
document.write("type of str6: " + typeof(str6) + "<br>");
</script>
</body>
</html>
Output
输出量
using toString()...
str1: Manju,Amit,Abhi,Radib
str2: 10,20,30,40,50
using join()...
str3: Manju,Amit,Abhi,Radib
str4: 10,20,30,40,50
using join() with separator...
str5: Manju Amit Abhi Radib
str6: 10 20 30 40 50
printing the types of the objects...
type of arr1: object
type of arr2: object
type of str1: string
type of str2: string
type of str3: string
type of str4: string
type of str5: string
type of str6: string
翻译自: https://www.includehelp.com/code-snippets/join-vs-toString-methods-in-javascript.aspx