【问题标题】:How to convert array containing a Symbol to string?如何将包含符号的数组转换为字符串?
【发布时间】:2019-10-01 09:15:36
【问题描述】:

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

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

将此类数组转换为字符串的最佳方法是什么(就像 console.log 一样)?

【问题讨论】:

  • 您会收到错误,因为您没有将 Symbol() 转换为 string ,而是将字符串转换为对象。它应该是 const s = [10, 'abc', Symbol('test').toString()];

标签: javascript arrays


【解决方案1】:

.map 数组,首先在每个符号上调用toString

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

要将符号转换为字符串,您必须明确地这样做。

允许在符号上调用toString,因为这会调用Symbol.prototype.toString()

相比之下,尝试将 Symbol 隐式转换为字符串,例如使用 Array.prototype.join(或 Array.prototype.toString,内部调用 Array.prototype.join+ 等),会调用 ToString 操作,当参数是符号时抛出。

【讨论】:

    【解决方案2】:

    只需将符号转换为字符串,而不是转换整个数组

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

    【讨论】:

      【解决方案3】:

      你能在数组上调用 .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() 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多