首页 > 解决方案 > 我怎么知道我什么时候在 JS 中的一个字符串的末尾?

问题描述

我正在尝试编写一些可以.length在 Javascript 中完成工作的东西。换句话说,我正在尝试编写一个可以计算字符串中字符的函数。

现在,我编写了一些在检测到 时停止的代码" ",但这不是最好的事情,因为用户不能在他的字符串中输入任何空格。在 C 中有\0一个字符串的末尾,我们如何在 Javascript 中看到它?

function StringLength() {
    var nb = 0;
    var i = 0;
    //take the value of 'inputUser' and save it in 'input'
    var input = document.getElementById('inputUser').value;
    input = input + " ";
    //loop that stop when there is a " "
    while (input[i] != " ") {
        nb++;
        i++;
    }
}

标签: javascript

解决方案


当您访问字符串末尾之后的属性时,该值将是undefined

function StringLength(str) {
    var i = 0;
    while (str[i] !== undefined) {
        i++;
    }
    return i;
}
console.log(StringLength('foo'));


推荐阅读