javascript - 如何使用 slice() 重写 .length() 属性?

标签 javascript recursion

这是我的作业:

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/

相关文章:

php - jQuery 中的轮询是否昂贵,是否有替代方案?

javascript - 在span标签上使用on函数

javascript - Mouse Out Orange Div "CurrentHeight"未应用

java - 为什么代码在 "return"之后仍在运行

sql-server - 将触发表上的更新将是递归的

javascript - 如何在所需位置添加动态创建的节点(标签)?

javascript - 如何从下拉列表中删除选定值以外的所有值

java - 如何跟踪这个递归函数?

java - 数独求解器递归

javascript - 从 JSON 数据创建 HTML 项目符号列表时出现问题