【问题标题】:looping through multidimensional array and getting values from property names instead of numbers循环遍历多维数组并从属性名称而不是数字中获取值
【发布时间】:2013-12-28 23:49:57
【问题描述】:

所以我有一个多维数组,一个包含 json 对象/数组的数组,其中包含属性和值。我想使用属性名称获取属性值。我可以像这样在每个循环中使用每个循环(用于循环遍历数组的两个维度):

jQuery.each( jsonArray, function(i,val) {


 jQuery.each( val, function(j,val_j) {

        if (j == "episodeNumber")  {
        // run some code
        }

});
});

但我觉得上面的代码是不必要的混乱。我不想每次想要获取值时都使用 if 语句。我想做类似的事情:

 jQuery.each( jsonArray, function(i,val) {

 var test = $(this)[propertyName]; 
  // I've got the value I want now by using the prop name
 });

当然上面的代码是行不通的。有任何想法吗?

【问题讨论】:

  • 你能告诉我们这个数组的样子吗?
  • $(this)[propertyName] 没有意义,因为这里的 'this' 不是 dom 对象,试试 this.propertyName 吧..
  • @ArpitSingh 你是正确的。那就是我做错了......我总是很困惑何时使用 $(this) 以及何时只使用 'this' ......所以 $(this) 仅在对象已经在 DOM 中时才合适?跨度>
  • 嗯,也许......除非 jquery 出现并在不久的将来开始对非 DOM 对象做一些花哨的事情。

标签: jquery arrays json multidimensional-array


【解决方案1】:
jQuery.each( jsonArray, function(i,val) {

 var test = this[propertyName];
  //  'this' is not a dom object here when using named arrays
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-08
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多