javascript 将每个单词推入一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20169809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:55:42  来源:igfitidea点击:

pushing each word to an array

javascriptjqueryarrays

提问by Hello World

If I had a string of text, how would I convert that string into an array of each of the individual words in the string?

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

Something like:

就像是:

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

for ( //1 ) {
  wordArray.push( //2 );
}
  1. go through every word in the string named words
  2. push that word to the array
  1. 遍历名为 words 的字符串中的每个单词
  2. 将该词推送到数组

This would create the following array:

这将创建以下数组:

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

回答by David says reinstate Monica

Don't iterate, just use split()which returns an array:

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

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

console.log(wordArray);

JS Fiddle demo.

JS小提琴演示

And, using String.prototype.split()with the regular expression suggested by @jfriend00(in comments, below):

并且,使用@jfriend00String.prototype.split()建议的正则表达式(在下面的评论中):

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

console.log(wordArray);

References:

参考: