【发布时间】:2017-08-03 03:16:22
【问题描述】:
例子:
var test = [];
test.push( 'string', 'test'); //[ 'string', 'test' ]
console.log('{' + test + '}'); // {string,test}
console.log(typeof('{' + test + '}')); //string
为什么添加{ 和} 会从测试中删除括号?我本来希望第三行的结果是{ [string, test] }
【问题讨论】:
-
试试
console.log(''+test)- 数组的字符串表示没有括号。 -
+标点符号过载。它可以表示arithmetic addition, string concatenation 或unary+operator。哪一个是基于上下文的。 -
'' + test将test强制转换为字符串:test.toString()给出相同的结果。 -
JS 是一种非常松散类型的语言。在涉及不同类型的操作中,从对象到基本类型(如 String 或 Boolean)的类型强制是自动执行的。在这种特殊情况下,
Array.prototype.toString()函数只是忽略了外括号,并与String.prototype.split(",")相反。
标签: javascript arrays string object