如何在循环上创建新变量的同时修改函数参数?
这是代码,没有尝试将 var nn = 99 添加到循环中
//note that the 'i' is a parameter of the function
function myFunction(arr, i) {
for (i = i ? i + 5 : 1; i < arr.length; i++) {
//...
}
}
当我尝试添加新的 var 时,它会执行我不想要的操作:
编辑:这似乎是错误的
for (var nn = 99, i = i ? i + 5 : 1; i < arr.length; i++) //创建了一个新的“i”
或者
for (i = i ? i + 5 : 1, var nn = 99; i < arr.length; i++)
//doesn't work :(
我知道如果我将它移到外面它是完全相同的。但我最讨厌的事情之一是几个月后阅读旧代码时无法理解我的意思。将该行移到循环内将使我更容易理解该行。
This is the code without any attempt to add var nn = 99
to the loop
//note that the 'i' is a parameter of the function
function myFunction(arr, i) {
for (i = i ? i + 5 : 1; i < arr.length; i++) {
//...
}
}
When I try to add a new var
it do things I don't want:
Edit: it seems this is wrong
for (var nn = 99, i = i ? i + 5 : 1; i < arr.length; i++)
//created a new 'i'
or
for (i = i ? i + 5 : 1, var nn = 99; i < arr.length; i++)
//doesn't work :(
I know it is exactly the same if I move it outside. But one of the things I hate most, is to not be able to understand what I meant when reading a old code after some months. Moving that line inside the loop will make me understand that line easier.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法修改函数的参数。由于
i
是一个原始值(数字),JavaScript 将按值调用,而不是按引用调用。当您将第二个参数命名为“i”时,它将从一开始就作为局部变量使用。在某处使用 var 关键字和“i”不会改变任何东西。
You can't modify the function's parameter. As
i
is a primitive value (number), JavaScript will call-by-value, not by-reference.And as you name your second argument "i", it will be available as a local variable from start on. Using the var keyword with "i" somewhere won't change anything.
这将始终等于 99。但这并不重要,因为仍然不清楚您要实现的目标。
如果您的目标是从指定的起始点循环遍历数组,那么您可以这样做。
如果您不能保证 i 是一个数字,那么您将必须执行某种检查。
Javascript 将按值传递基元,因此您无法从此函数内部修改源值。如果需要,您可以返回修改后的值。
This will always equal 99. But that does not matter, since it is still unclear what you are trying to accomplish.
If your goal is to loop through an array from a designated start spot then you can do this.
If you can't guarantee that i is a number, then you will have to perform some sort of checking.
Javascript will pass primitives by value, so you cannot modify the source value from inside this function. You can return the modified value if want.