gpt4 book ai didi

javascript - 在each()内部创建var

转载 作者:行者123 更新时间:2023-11-28 11:35:51 25 4
gpt4 key购买 nike

我有一个包含一些数字的数组:

var bullet = [ 0, 39, 42, 89, 115 ];

并创建了一个each循环

$.each(bullet, function( index, value ) {

});

现在我想创建一个变量,其中索引作为每个项目名称的一部分。就像这样:

var bullet + index = document.getElementById("bullet_" + index);

它应该看起来像这样:

var bullet0 = document.getElementById("bullet_0");
var bullet1 = document.getElementById("bullet_1");

等等...

但是我的代码不起作用 - 它总是说未捕获的语法错误:意外的标识符

最佳答案

您无法创建动态变量名称。但是,您可以通过创建包装对象并将可能的变量分配为该对象的属性来创建动态键:

var bullets = {};

$.each(bullet, function( index, value ) {
bullets[ index ] = ( document.getElementById( 'bullet_' + index ) );
});

更好的是,您可以使用数组(因为键是数字):

var bullets = [];

$.each(bullet, function( index, value ) {
bullets.push( document.getElementById( 'bullet_' + index ) );
});

无论哪种情况,都不是您建议的访问方法

bullet0;
bullet1;

您将按如下方式访问元素:

bullet[ 0 ];
bullet[ 1 ];

关于javascript - 在each()内部创建var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21111114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com