我知道,这很奇怪!但为什么这样不起作用?
function getStringLength(string) {
// see how many substrings > 0 can be built
// log that number & return
var subString = string.slice();
var counter = 0;
while (subString !== '') {
counter++;
subString = subString.slice(counter);
}
return counter;
}
var output = getStringLength('hello');
console.log(output); // --> expecting 5, but getting 3 (??)
我真的很想用切片来完成!原始挑战是不使用长度属性,我找到了解决方法,它可以正常工作:
function getStringLength(string) {
var long = 0;
while (string[long] !== undefined) {
long++;
}
return long;
}