如果我有一个文本字符串,该如何将该字符串转换为字符串中每个单词的数组?
就像是:
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);
引用文献:
String.prototype.split()
。