简体   繁体   English

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

[英]How to convert array containing a Symbol to string?

I have an array that could contain Symbol() item.我有一个可以包含 Symbol() 项的数组。 Array.toSring brings an exception. Array.toSring 带来了一个异常。

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

What is the best way to convert such array to a string (like console.log does)?将此类数组转换为字符串的最佳方法是什么(如 console.log 所做的)?

.map the array, calling toString on each symbol first: .map数组,首先在每个符号上调用toString

 const s = [10, 'abc', Symbol('test')].map(val => typeof val === 'symbol'? val.toString(): val).join(','); console.log(s);

To turn a Symbol into a string, you have to do so explicitly.要将符号转换为字符串,您必须明确地这样做。

Calling toString on a symbol is permitted, because that invokes Symbol.prototype.toString() .允许对符号调用toString ,因为这会调用Symbol.prototype.toString()

In contrast, trying to turn the Symbol into a string implicitly, like with Array.prototype.join , (or Array.prototype.toString , which internally calls Array.prototype.join , or + , etc), invokes the ToString operation, which throws when the argument is a Symbol.相反,尝试将 Symbol 隐式转换为字符串,例如使用Array.prototype.join (或Array.prototype.toString ,内部调用Array.prototype.join+等),调用ToString操作,该操作当参数是符号时抛出。

simply you can convert the symbol to string instead of converting the whole array只需将符号转换为字符串,而不是转换整个数组

const s = [10, 'abc', Symbol('test').toString];

Can you do a small operation on the array before.toString() is called on the array.你能在数组上调用 before.toString() 之前对数组做一个小操作吗? Something like this:像这样的东西:

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();

The thing is we don't want to call.toString() method on each item of the array.问题是我们不想在数组的每个项目上调用.toString() 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM