gpt4 book ai didi

Javascript:在没有长度属性和切片的情况下获取字符串的长度

转载 作者:搜寻专家 更新时间:2023-11-01 04:56:09 25 4
gpt4 key购买 nike

我知道,这很奇怪!但为什么这不起作用?

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 (??)

我真的很想用切片来做!最初的挑战是不使用 length 属性,我想通了,效果很好:

function getStringLength(string) {

var long = 0;

while (string[long] !== undefined) {
long++;
}

return long;
}

最佳答案

你正在改变你的字符串,这应该对你有用

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(1);
}

return counter;
}

var output = getStringLength('hello');

console.log(output); // 5

主要区别在于我在做

subString = subString.slice(1);

代替

subString = subString.slice(counter);

总是将长度减 1

关于Javascript:在没有长度属性和切片的情况下获取字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286415/

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