关于javascript循环的问题
我尝试了这个循环,但不起作用(语法错误)。 正确的做法是什么?例如,up+i 不起作用。
for(i=0;i<10;i++) {
up+i = function() {
base.refresh("Field"+i, $t+i);
}
}
I tried this loop, but isn't working (Syntax errors).
What is the correct way to do it? up+i doesn't work for example.
for(i=0;i<10;i++) {
up+i = function() {
base.refresh("Field"+i, $t+i);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
主要问题是围绕这一行
表达式
up+i
产生一个值,而不是一个变量,以及一个可以分配的位置。您是否尝试分配到数组中?如果是这样,请将其更改为以下编辑
OP,阐明其意图是创建 10 个命名函数。在这种情况下,需要有一个物体来悬挂它们。我将其称为 root 作为示例。
此外,现在该函数正在捕获单个
i
,这意味着该函数的所有实例都将具有相同的i
值。为了防止这种情况,请使用单独的函数来捕获该值。The primary issue is around this line
The expression
up+i
produces a value, not a variable, and a place which can be assigned to. Were you trying instead to assign into an array? If so change it to the followingEDIT
OP clarified that the intent is to create 10 named functions. In that case there needs to be an object to hang them off of. I'll call it root for an example
Additionally right now the function is capturing a single
i
meaning all instances of the function will have the same value fori
. To prevent this use a separate function to capture the value.负责循环工作的代码。请看这里: http://jsfiddle.net/7aZLv/ (警告!依次打开 10 个警报框)
编辑:
您可以创建如下全局函数:http://jsfiddle.net/7aZLv/1/
发生错误是因为您的赋值表达式不正确(您将值赋给表达式,而不是变量应如何分配)。
The code responsible for looping works. Just see here: http://jsfiddle.net/7aZLv/ (warning! opens 10 alert boxes one after another)
EDIT:
You can create global functions like that: http://jsfiddle.net/7aZLv/1/
The error happened because you assignment expression was incorrect (you assigned value to expression, not a variable how it should be assigned).
也许应该只是这样
?我们需要大量信息来帮助您,应该做什么,您想要实现什么目标?您遇到什么语法错误?
Maybe it should just be
? We need lots of information to help you, what is up supposed to be, what are you trying to accomplish? What syntax errors are you getting?
赋值语句的左侧不能有表达式。
up+i
应该是指针算术吗?如果是这样,则 javascript 中没有指针。我不知道你想做什么,但首先要做的就是将up+i = function() { ...}
更改为up = function() {。 ..}
或者也获取一个新变量来分配它。You cannot have an expression on the left hand side of an assignment. is
up+i
supposed to be pointer arithmetic? if so, there are no pointers in javascript. i cannot tell what you are trying to do, but the first thing to do would be to changeup+i = function() { ...}
toup = function() {...}
or else get a new variable to assign it too.您的代码中有很多错误。
也许像这样?
Many errors in your code.
maybe like this?
您可以将它们添加到数组中,而不是尝试为函数创建单独的变量。
Instead of trying to create individual variables for the functions, you can add them to an array.
尝试一下
这会将函数添加到
window
对象中,以便您可以在其之后进行如下调用:try this
This will add the functions to the
window
object so that you can make calls like this after it: