如果我有一个文本字符串,我如何将该字符串转换为字符串中每个单词的数组?
就像是:
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"]
参考文献: