javascript - 我怎么知道我什么时候在 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++;
}
}
解决方案
当您访问字符串末尾之后的属性时,该值将是undefined
:
function StringLength(str) {
var i = 0;
while (str[i] !== undefined) {
i++;
}
return i;
}
console.log(StringLength('foo'));
推荐阅读
- javascript - 从 API 响应中获取数据并显示在表格中
- reactjs - 从子页面重定向时不想刷新网页中的父页面
- image - TensorFlow 2.0 和图像处理
- python - 在 url 中使用 id 进行分页,而不是 od "?page="
- hadoop - HIVE 加载数据路径
- python - python tkinter接近停止循环线程
- android - 增强现实:在 3D 模式下渲染 Android webView
- ldap - 使用 NTLMv2 invalidCredential 的 LDAP 身份验证
- javascript - 如果其他条件在javascript中,脚本和链接标签?
- r - 在R中应用,相同的函数不同的参数