【问题标题】:Javascript's equivalent of Python's list() [duplicate]Javascript 相当于 Python 的 list() [重复]
【发布时间】:2017-06-25 13:29:38
【问题描述】:

类似于或类似的功能:

list("String")
'''
return: ['S','t','r','i','n','g']
'''

这个函数有 Javascript 等价物吗?

【问题讨论】:

  • 你的意思是你想要char数组?使用拆分函数 例如:"String".split('')
  • 最新浏览器使用Array.from
  • @AbdennourTOUMI 我不认为这是重复的,因为list() 在 Python 中的用途比获取字符数组更多。它是从可迭代类型到列表类型的通用转换器。

标签: javascript python list function


【解决方案1】:

在所有情况下,传递给list() 的最接近的等价物是使用 ES6 中的 spread syntax。对于旧版本的 JavaScript,您可以将 string.split('') 用于字符数组。注意.split('')won't work with characters that use surrogate pairs

function list(iterable) {
  return [...iterable];  
}

console.log(list('String'));

【讨论】:

    【解决方案2】:

    使用带有空字符串分隔符的String#split 方法作为参数,将字符串转换为字符数组。

    "String".split('')
    

    console.log(
      "String".split('')
    )

    对于最新的浏览器,请使用Array.from 方法或spread syntax

    // Using Array.from 
    var arr = Array.from("String")
    
    // Using spread syntax 
    var arr = [..."String"]
    

    console.log(
      Array.from("String")
    )
    
    console.log(
      [..."String"]
    )

    【讨论】:

      【解决方案3】:
      var str = "String"    
      str.split('');
      

      应该这样做

      【讨论】:

        【解决方案4】:

        使用拆分方法,"Hello world!".split('')

        console.log(
          "Hello world!".split('')
        )
        

        【讨论】:

          【解决方案5】:

          如果要将String转换为Array,每个元素都是字符串的一个字符,可以使用String.prototype.split():

          "String".split('') //['S', 't', 'r', 'i', 'n', 'g']
          

          【讨论】:

            猜你喜欢
            • 2012-11-19
            • 1970-01-01
            • 1970-01-01
            • 2012-07-28
            • 1970-01-01
            • 2013-09-22
            • 1970-01-01
            • 2010-09-07
            • 2013-04-13
            相关资源
            最近更新 更多