toString()
方法返回一个由给定 数组 的元素组成的 字符串。
示例
// defining an array
let items = ["JavaScript", 1, "a", 3];
// returns a string with elements of the array separated by commas
let itemsString = items.toString();
console.log(itemsString);
// Output:
// JavaScript,1,a,3
toString() 语法
toString()
方法的语法是
arr.toString()
这里,arr 是一个数组。
toString() 参数
toString()
方法不接受任何参数。
toString() 返回值
- 返回一个字符串,表示数组的值,并用逗号分隔
注意事项:
toString()
方法不会更改原始数组。undefined
、null
或空数组等元素具有空字符串表示形式。
示例 1:使用 toString() 方法
let info = ["Terence", 28, "Kathmandu"];
// returns the string representation of the info array
let info_str = info.toString();
console.log(info_str);
// toString() does not change the original array
console.log(info);
输出
Terence,28,Kathmandu [ 'Terence', 28, 'Kathmandu' ]
在上面的示例中,我们使用 toString()
方法将 info 数组的所有元素转换为字符串。
info.toString()
返回 info 的字符串表示形式,即 Terence,28,Kathmandu
。
由于该方法不会更改原始数组,因此 info 数组仍然保留其原始值。
示例 2:带嵌套数组的 toString()
当我们在嵌套数组中使用 toString()
方法时,该数组会被展平。例如
// defining a nested array
let nestedArray = [1, 2, 4, ["Apple", 5]];
// returns string representation of the nested array by flattening the array
let resultingArray = nestedArray.toString();
console.log(resultingArray);
输出
1,2,4,Apple,5
另请阅读