I'm using a somewhat unconventional for loop that works well for what I'm doing as paraphrased below (not bothering to show variable declarations):
if (arr && arr.length > 0) {
for (i = arr.length; i--; i) {
element = arr.pop();
//rest of code
}
}
Closure compiler is giving me a warning of: "WARNING - Suspicious code. This code lacks side effects, is there a bug?" Pointing specifically to the last "i" in the for loop parens.
If I remove the i, jslint throws a warning, if I leave it, closure throws a warning. There are three of these loops in total, is there a "closure friendly" way to do this?
How 'bout the normal way?
if (arr && arr.length > 0) {
for (i = arr.length; i > 0; --i) {
element = arr.pop();
//rest of code
}
}
Putting the decrement in the test is just not the normal way to write a for
loop.
Or even more normal:
if (arr && arr.length > 0) {
for (i = arr.length - 1; i >= 0; --i) {
element = arr.pop();
//rest of code
}
}
...but as you're not using i
, it doesn't matter much.
Or you could use a while
:
if (arr && arr.length > 0) {
i = arr.length;
while (i--) {
element = arr.pop();
//rest of code
}
}
For future readers, if you're reducing an array's length, don't use a for
loop, use a while
:
if (arr) {
while (arr.length) {
element = arr.pop();
...
}
}
是的-这样的事情应该可以解决问题:
for (i = arr.length; i > 0; i--) {
使用jshint而不是jslint并关闭警告。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.