jst*_*one -2 javascript string split
我正在处理来自CoderByte的问题.我很好奇我的代码.第一个函数returns 6和第二个函数returns 4是正确的计数.我试图理解为什么会这样.当我在控制台日志时newArr它只显示4个项目.
以下是来自CoderByte的问题: - 使用JavaScript语言,让函数WordCount(str)获取传递的str字符串参数并返回字符串包含的单词数(即"Never eat shredded wheat"将返回4).单词将由单个空格分隔.
var wordCount = function (str) {
var newArr = str.split(' ');
var total = 0;
for (var i = 0; i < newArr.length; i += 1) {
total += i;
}
return total;
};
Run Code Online (Sandbox Code Playgroud)
///
wordCount('Never eat shredded wheat');
var wordCount = function (str) {
return str.split(' ').length;
};
Run Code Online (Sandbox Code Playgroud)
因为您要添加i而不是一个.
total += i;
Run Code Online (Sandbox Code Playgroud)
基本上你有
iteration 1 : total = total + 0 = 0 + 0 = 0
iteration 2 : total = total + 1 = 0 + 1 = 1
iteration 3 : total = total + 2 = 1 + 2 = 3
iteration 4 : total = total + 3 = 3 + 3 = 6
Run Code Online (Sandbox Code Playgroud)