将每个单词推送到一个数组 [英] pushing each word to an array

查看:98
本文介绍了将每个单词推送到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

类似于:

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

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

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

1 = go through every word in the string named words 2 = push that word to the array

这将创建以下数组:

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


推荐答案

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

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

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

参考文献:

这篇关于将每个单词推送到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆