如何将包含符号的数组转换为字符串?

我有一个可以包含 Symbol() 项的数组。Array.toSring 带来了一个例外。


const s = [10, 'abc', Symbol('test')].toString(); // this throws an exception

console.log([10, 'abc', Symbol('test')]); // this works


将此类数组转换为字符串的最佳方法是什么(如 console.log 所做的)?


三国纷争
浏览 184回答 3
3回答

侃侃无极

只需将符号转换为字符串,而不是转换整个数组const s = [10, 'abc', Symbol('test').toString];

慕婉清6462132

.map数组,首先调用toString每个符号:const s = [10, 'abc', Symbol('test')]  .map(val => typeof val === 'symbol' ? val.toString() : val)  .join(',');console.log(s);要将 Symbol 转换为字符串,您必须明确地这样做。toString允许调用符号,因为它会调用Symbol.prototype.toString()。相比之下,尝试将 Symbol 隐式转换为字符串,例如 with Array.prototype.join,(或Array.prototype.toString,内部调用Array.prototype.join, or+等),会调用ToString操作,当参数是 Symbol 时抛出该操作。

胡子哥哥

你能在数组上调用 .toString() 之前对数组做一个小操作吗?像这样的东西:function myFunction() {  var fruits = [10, 'abc', Symbol('test')];  var test = [];  for(item of fruits){      if(typeof(item) === "symbol"){          test.push(item.toString());      }      else{test.push(item)}  }  var x = test.toString();问题是我们不想在数组的每个项目上调用 .toString() 方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript