将每个单词推送到一个数组

时间:2013-11-24 00:51:29

标签: javascript jquery arrays

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

类似的东西:

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

for ( //1 ) {
wordArray.push( //2 );
}

1 =遍历名为words的字符串中的每个单词 2 =将该字推送到数组

这将创建以下数组:

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

3 个答案:

答案 0 :(得分:21)

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

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

console.log(wordArray); // ["never", "forget", "to", "empty", "your", "vacuum", "bags"] 

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

非正则表达式选项的另一种解决方案。

let words = '     practice   makes   perfect  ',
  wordArray = words.split(' ').filter(w => w !== '');

console.log(wordArray);

或仅使用String.prototype.match()

let words = '     practice   makes   perfect  ',
  wordArray = words.match(/\S+/g);

console.log(wordArray);

答案 2 :(得分:0)

如果您想遍历数组,请使用:

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

let wordsSplit = words.split(" ");
for(let i=0;i<wordsSplit.length;i++) {
    wordArray.push(wordsSplit[i])
}

但不迭代而只使用更有意义:

let words = 'never forget to empty your vacuum bags';
let arrOfWords = words.split(" ")