简体   繁体   English

遍历Javascript中的变量

[英]Iterating over variables in Javascript

My goal with block 2 is to streamline my existing block 1 code by defining javascript variables in a for loop.The code below is giving me the error "Unexpected token [" in the console. 我对块2的目标是通过在for循环中定义javascript变量来简化现有的块1代码。下面的代码在控制台中给我错误“ Unexpected token [”。 I am not sure I am using the proper syntax here. 我不确定我在这里使用正确的语法。 Is there a way to loop over an array and insert each dynamically to get the desired result of block 1? 有没有一种方法可以遍历数组并动态插入每个数组以获得所需的块1结果?

I am able to console.log details_object[i] in block 2 and successfully see all the array elements but that is about as far as I can get. 我能够在块2中console.log details_object [i]并成功查看所有数组元素,但是据我所知。

   /*Block 1*/

   /*var title = document.getElementById('title').value;
   var phone = document.getElementById('phone').value;
   var firstn = document.getElementById('firstn').value;
   var lastn = document.getElementById('lastn').value;
   var displayn = document.getElementById('displayn').value;*/

   /*Block 2 less code!*/

   var details_object = ["title", "phone", "firstn", "lastn", "displayn"];

   for(var i=0, l = details_object.length; i < l; i++){
     var details_object[i] = document.getElementById("'"+details_object[i]+"'").value;
   }
var details_object[i] = document.getElementById("'"+details_object[i]+"'").value;
 ^---// Delete this var

That is what was causing the error. 这就是导致错误的原因。 You probably want something like this: 您可能想要这样的东西:

var details_object = ["title", "phone", "firstn", "lastn", "displayn"];
var obj = {};

for(var i=0, l = details_object.length; i < l; i++){
  obj[details_object[i]] = document.getElementById(details_object[i]).value;
}

Now access obj.title , obj.phone , etc. 现在访问obj.titleobj.phone等。

Try 尝试

var scope = this;
for(var i=0, l = details_object.length; i < l; i++){
     scope[details_object[i]] = document.getElementById(details_object[i]).value;
}

this will create a variable named with the name stored in details_object[i] into the current scope. 这将在当前作用域中创建一个变量,其名称存储在details_object[i] Hopefully you are not doing this on the global scope as this will pollute it. 希望您不会在全球范围内这样做,因为这会污染它。

Try this 尝试这个

var details_object = ["title", "phone", "firstn", "lastn", "displayn"];
for(var i=0, l = details_object.length; i < l; i++){
     window[details_object[i]] = document.getElementById("'"+details_object[i]+"'").value;
   }

My goal with block 2 is to streamline my existing block 1 code by defining javascript variables in a for loop 我对块2的目标是通过在for循环中定义javascript变量来简化我现有的块1代码

You can only do that with eval or with properties of the global object (which is the window object in a browser). 您只能使用eval或全局对象(浏览器中的窗口对象)的属性来执行此操作。 Javascript does not allow access to a local variable object, so you can't directly address its properties. Javascript不允许访问局部变量对象,因此您不能直接处理其属性。 You can only access them using an identifier name that is first resolved in the current execution context (more or less on a local variable object) and then on the scope chain which has the variables of outer execution contexts if there are any. 您只能使用标识符名称来访问它们,该标识符名称首先在当前执行上下文中解析(或多或少在本地变量对象上),然后在具有外部执行上下文变量(如果有)的作用域链上进行解析。

The exception is that global variables are made properties of the global object. 唯一的例外是全局变量是全局对象的属性。 These can be created and accessed using square bracket notation, however global properties created through assignment have subtle differences to those created using declarations (eg declared global variables can't be deleted, properties created through assignment can). 可以使用方括号表示法创建和访问它们,但是通过赋值创建的全局属性与使用声明创建的全局属性有细微的差异(例如,不能删除已声明的全局变量,可以通过赋值创建的属性)。

So if you are happy to create proerties of the global object, you can do: 因此,如果您乐于创建全局对象的属性,则可以执行以下操作:

// In global code
var global = this;

// Anywhere you wish to create, read or assign to a global property
global[whatever] ...   // using an identifier whose value resolves to a string
global['whatever'] ... // using a string
global[foo()] ...      // using some other type of expression that returns a string

However, it is considered far better practice to create a single object for such properties so as to avoid the possiblity of naming conflicts with properties of the global object, eg 但是,考虑到更好的做法是为此类属性创建单个对象,以避免与全局对象的属性发生命名冲突的可能性,例如

var myVars = {}

myVars[varName]  = varValue;

Otherwise, you can use eval to create local variables in function code: 否则,您可以使用eval在函数代码中创建局部变量:

eval('var ' + whatever + ' = 3');
alert(whatever); // 3

However, that is not recommended. 但是,不建议这样做。 It is preferred to use a myVars object that is shared either through a closure, inheritance or as a global variable. 最好使用通过闭包,继承或作为全局变量共享的myVars对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM