Home  >  Article  >  Web Front-end  >  JavaScript method toString() converts an array into a string and returns the result

JavaScript method toString() converts an array into a string and returns the result

黄舟
黄舟Original
2017-11-04 09:31:362497browse

Definition and usage

toString() method can convert an array into a string and return the result.

Syntax

arrayObject.toString()

Return value

String representation of arrayObject. The return value is the same as the string returned by the join() method without parameters.

Explanation

When an array is used in a string environment, JavaScript will call this method to automatically convert the array into a string. However, in some cases, it is necessary to call this method explicitly.

Tips and Notes

Note: Elements in the array are separated by commas.

Example

<script type="text/javascript">

var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"

document.write(arr.toString())

</script>

Output:

George,John,Thomas

Example & Description

The following example runs in the host environment of Windows 7 Simplified Chinese Ultimate Edition 64-bit, located at Chinese mainland. Depending on the locale and language settings, the output results of the execution may be different.

//数组
var array = ["CodePlayer", true, 12, -5];
document.writeln( array.toString() ); // CodePlayer,true,12,-5

// 日期
var date = new Date(2013, 7, 18, 23, 11, 59, 230);
document.writeln( date.toString() ); // Sun Aug 18 2013 23:11:59 GMT+0800 (中国标准时间)

// 日期2
var date2 = new Date(1099, 7, 18, 23, 11, 59, 230);
document.writeln( date2.toString() ); // Fri Aug 18 1099 23:11:59 GMT+0800 (中国标准时间)

// 数字
var num =  15.26540;
document.writeln( num.toString() ); // 15.2654

// 布尔
var bool = true;
document.writeln( bool.toString() ); // true

// Object
var obj = {name: "张三", age: 18};
document.writeln( obj.toString() ); // [object Object]

// HTML DOM 节点
var eles = document.getElementsByTagName("body");
document.writeln( eles.toString() ); // [object NodeList]
document.writeln( eles[0].toString() ); // [object HTMLBodyElement]


The above is the detailed content of JavaScript method toString() converts an array into a string and returns the result. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn