这是我的作业:
By now you should have worked with the length property of strings, e.g. "hello".length. Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!
Instead, you'll need to make use of the string method called slice. For our purposes, we can consider slice as taking one argument -- the index to begin slicing from, and returns a new string starting from that index onwards.
这是我尝试过的:
function stringLength(string){
var count = count++;
if(string.slice(0)){
return count}
return stringLength(string.slice(0,-1))
}
console.log(stringLength("game"))
我试图将字符串的每个字符切片回起始索引,索引 0,然后累积我的计数变量。我不明白为什么我的计数变量没有累积。
最佳答案
迭代提案。
function stringLength(string) {
var count = 0;
while (string) {
string = string.slice(1);
count++;
}
return count;
}
console.log(stringLength("game"));
递归提案。
function stringLength(string) {
return string ? 1 + stringLength(string.slice(1)) : 0;
}
console.log(stringLength("game"));
关于javascript - 如何使用 slice() 重写 .length() 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40823645/