简体   繁体   English

jQuery / Javascript-使用变量名称的引用对象

[英]JQuery/Javascript - Reference object using variable name

Please excuse my inability to accurately describe what it is I am after. 请原谅我无法准确描述我所追求的。 This in ability has made it very difficult to search for an answer, thus I am asking now. 这种能力使寻找答案非常困难,因此我现在要问。

I have an object (data.drivers) which contains a bunch of lap information. 我有一个对象(data.drivers),其中包含许多膝部信息。

I am looping through this object to update already displayed information, but would like to condense my code and be able to loop through the fields rather than write the same code for every possible field. 我正在遍历该对象以更新已经显示的信息,但是想压缩我的代码并能够遍历这些字段,而不是为每个可能的字段编写相同的代码。

Problem is I do not know how to get the value from i by refering to it with a variable. 问题是我不知道如何通过使用变量引用i来获取值。 For example: 例如:

$.each(data.drivers, function(pos, i) {
  var driver_position = i.position;  // this and much more would happen for 9 fields
  alert (driver_position);
});

This works. 这可行。

But what I would like to do is this: 但是我想做的是:

$.each(data.drivers, function(pos, i) {

  var fields = [ 'position', 'name', 'laps', 'lapTime', 'pace', 'difference', 'elapsedTime', 'fastLap', 'eqn' ];

  $.each (fields, function (ii, field) {
    alert (i.field);
  });

});

What you're looking for is bracket notation: 您要查找的是括号符号:

alert(i[field]);

Though using some more descriptive variable names helps in the long run, quite a bit. 尽管使用一些更具描述性的变量名从长远来看会有所帮助。

You could also just loop over properties with each as well. 您也可以只遍历each属性。 You don't need that fields array of properties unless there are only specific properties you need and even then you can handle it within the each . 除非只需要特定的属性,并且甚至可以在each属性中处理它,否则不需要属性的arrays数组。

// Loop over array of driver objects
$.each(data.drivers, function(index, driver) {
    // Loop over driver object properties
    $.each(driver, function(key, value) {
        // key is property name
        // value is property value
    });
});

Documentation: http://api.jquery.com/jquery.each/ 文档: http : //api.jquery.com/jquery.each/

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. 通用迭代器函数,可用于无缝迭代对象和数组。 Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. 具有长度属性的数组和类似数组的对象(例如函数的arguments对象)通过从0到length-1的数字索引进行迭代。 Other objects are iterated via their named properties. 其他对象通过其命名属性进行迭代。

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

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