Here is a pic of console log and code
它应该做什么:接受一个字符串,并且console.log应该使用单独的单词。它的作用:接收字符串和console.log的每个字母。而且我不明白为什么要这么做。我用yield来返回整个单词(我用console.log检查了dst),因此它应该用console.log记录下来,但是作为回报,它会通过每个字母(((((非常感谢您的时间!
scripts.js
import 'babel-polyfill';
import {wordsCount, getWords} from './other.js';
window.addEventListener('load', function(){
let str = ' Its a good weather! Yeah ! ';
//console.log(wordsCount(str));
let iterator = getWords(str);
for(let some of getWords(str)){
this.console.log(some);
}
});
other.js
function stringClear(str)
{
return str.trim().replace(/ {2,}/, " ");
}
export function wordsCount(str){
return stringClear(str).split(' ').length;
}
export function* getWords(str){
str = stringClear(str);
let dst = "";
for(let i = 0; i < str.length; i++)
{
if(str.charAt(i) == " ")
{
yield* dst;
dst = "";
continue;
}
dst += str.charAt(i);
}
}
console.log
I
scripts.js?6962:11 t
scripts.js?6962:11 s
scripts.js?6962:11 a
scripts.js?6962:11 g
2scripts.js?6962:11 o
scripts.js?6962:11 d
scripts.js?6962:11 w
scripts.js?6962:11 e
scripts.js?6962:11 a
scripts.js?6962:11 t
scripts.js?6962:11 h
scripts.js?6962:11 e
scripts.js?6962:11 r
scripts.js?6962:11 !
scripts.js?6962:11 Y
scripts.js?6962:11 e
scripts.js?6962:11 a
scripts.js?6962:11 h
产量前的星号。您要在要产生的字符串上产生一个迭代器,因此每个yield还要在每个单词字符串上进行迭代,然后在yield *之后继续
window.addEventListener('load', function(){
let str = ' Its a good weather! Yeah ! ';
//console.log(wordsCount(str));
let iterator = getWords(str);
for(let some of getWords(str)){
this.console.log(some);
}
});
function stringClear(str)
{
return str.trim().replace(/ {2,}/, " ");
}
function wordsCount(str){
return stringClear(str).split(' ').length;
}
function* getWords(str){
str = stringClear(str);
let dst = "";
for(let i = 0; i < str.length; i++)
{
if(str.charAt(i) == " ")
{
yield dst;
dst = dst.slice(dst.length);
continue;
}
dst += str.charAt(i);
}
}