javascript – 将每个单词推送到数组

前端之家收集整理的这篇文章主要介绍了javascript – 将每个单词推送到数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个文本字符串,我如何将该字符串转换为字符串中每个单词的数组?

就像是:

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'];

解决方法

不要迭代,只需使用返回数组的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.

参考文献:

> String.split().

原文链接:https://www.f2er.com/js/158902.html

猜你在找的JavaScript相关文章