如果我有一个文本字符串,该如何将该字符串转换为字符串中每个单词的数组?

就像是:

var wordArray = [];
var words = 'never forget to empty your vacuum bags';

for ( //1 ) {
  wordArray.push( //2 );
}
  • 遍历名为单词
  • 的字符串中的每个单词
  • 将该单词推送到数组

  • 这将创建以下数组:
    var wordArray = ['never','forget','to','empty','your','vacuum','bags'];
    

    最佳答案

    不要迭代,只需使用split()返回一个数组:

    let words = 'never forget to empty your vacuum bags',
      wordArray = words.split(' ');
    
    console.log(wordArray);


    JS Fiddle demo

    并且,使用String.prototype.split()@jfriend00建议的正则表达式(在下面的注释中):

    let words = 'never forget to empty your vacuum bags',
      wordArray = words.split(/\s+/);
    
    console.log(wordArray);


    引用文献:
  • Regular Expressions
  • String.prototype.split()
  • 07-25 23:32