Javascript循环并构建数组,但变量索引未定义
不要笑,以为我有一整天工作的金发时刻,因为我有点不习惯 JS。任何帮助都对我认为是一个愚蠢的简单问题表示赞赏。
optionarray = [];
for(i=0;i<response.length;i++) {
optionarray[i]['content'] = response[i]['name'];
optionarray[i]['value'] = response[i]['id'];
}
当尝试将其添加到数组并构建它时,我不断收到 optionarray[i] is undefined 的信息。我知道我做了一些可笑的愚蠢的事情,我只是不记得是什么:)
非常感谢您提前提供的任何帮助。
dont laugh think im having a long day work blonde moment as im a bit out of practice with JS. Any helped appreciated for what I think is a stupidly simple problem.
optionarray = [];
for(i=0;i<response.length;i++) {
optionarray[i]['content'] = response[i]['name'];
optionarray[i]['value'] = response[i]['id'];
}
I keep getting optionarray[i] is undefined when trying to add it to the array and build it. I know im doing something ridiculously stupid I just can't remember what :)
Many thanks for any help in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在尝试访问
optionarray[i]
的属性,该属性不存在。您在每次迭代中应该做的是
optionarray
中您可以同时执行这两个操作,如下所示:
You are trying to access properties of
optionarray[i]
, which does not exist.What you should be doing in each iteration is
optionarray
You can do both at once like this:
我认为你只需要在 for 循环中初始化 optionarray[i] 对象:
如果我没有记错的话。
I think you just need to initialize the optionarray[i] object within your for loop:
if I'm not mistaken.
试试这个
你需要首先将 optionarray[i] 定义为数组
Try this one
You need to define optionarray[i] as array first