gpt4 book ai didi

javascript - 在 JavaScript 中创建字符串长度函数

转载 作者:行者123 更新时间:2023-12-01 01:02:59 25 4
gpt4 key购买 nike

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.

我的程序没有创建正确的输出。请解释我的代码中的错误。

function stringLength(string) {
let start =0;
let end= string.slice(0, "");
let result=0;
for(let i=start; i<=end; i++){
result++;
}
return result;
}

我的输出是1

而输出应返回给定字符串的长度。

最佳答案

你可以试试这个:

function stringLength(string) {

let index = 0;

while (string.slice(index) !== '') {
index++;
}

return index;
}

string.slice(index) 将返回从索引 index 处的字符到字符串末尾的子字符串。如果 index 超过字符串中的最大索引,则返回空字符串。这就是你知道必须停止计数的方式。

你甚至可以根本不使用切片:

function stringLength(string) {

let count = 0;

for(let char of string) {
count++;
}

return count;
}

关于javascript - 在 JavaScript 中创建字符串长度函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55893948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com