use*_*126 2 javascript for-loop
这件事已经让我伤了一个小时.我正在尝试对字符串执行简单的for循环,并返回当前字符和下一个字符.
var mystring = "abcdef";
for (x in mystring) {
if (mystring[x + 1]) {
console.log(x + ": " + mystring[x] + mystring[x + 1]);
}
else {
console.log("You've reached the end of the string");
}
}
Run Code Online (Sandbox Code Playgroud)
在循环的每次迭代中,"mystring [x + 1]"都是假的.虽然我希望它对于字符串的前五个字符是正确的.这里发生了什么?有什么关于JavaScript的东西我不明白吗?
for-in用于循环对象的可枚举属性的名称.属性名称始终为字符串*.string + number使用串联产生字符串(例如,"1" + 1是"11",不是2).
因此,如果您首先将属性名称转换为数字,那么它可能主要用于:
x = +x; // Convert to number
if (mystring[x + 1]) {
Run Code Online (Sandbox Code Playgroud)
......但我会用
for (x = 0; x < mystring.length; ++x) {
Run Code Online (Sandbox Code Playgroud)
...代替.如果我需要支持旧浏览器,我也会使用.charAt(...)而不是[...]获取角色(但我认为那些不支持索引到字符串的浏览器现在已经相当死了).
实例只有x = +x:
var mystring = "abcdef";
for (x in mystring) {
x = +x;
if (mystring[x + 1]) {
snippet.log(x + ": " + mystring[x] + mystring[x + 1]);
}
else {
snippet.log("You've reached the end of the string");
}
}Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>Run Code Online (Sandbox Code Playgroud)
*"属性名称总是字符串"这在ES5中是正确的.在ES6 +中,它们也可能是Symbol实例,但for-in不访问非字符串的实例.这与此无关,但我不想在那里留下这样的声明... :-)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |