【问题标题】:Read the row in the JSON only if the array for media is NOT EMPTY仅当媒体数组不为空时才读取 JSON 中的行
【发布时间】:2016-06-14 17:34:15
【问题描述】:

只有当媒体数组不为空时,我才想读取 JSON 中的行。

但是下面的代码不起作用。虽然我已经定义了

  • (data.rows[j].media.length >=1) 或
  • (data.rows[j].media != undefined)

它仍然会读取 EMPTY 媒体的数组。 .

// JSON data

{
  author: "Mary",  
  media: [ ],
},
{
  author: "Nelson",  
  media: [ 
   {
      type: "Image", 
      link: "https://...jpeg"
   }
  ]
}
// Jquery to get the data from JSON

$.ajax('https://rest.xyz.com/', {
type: 'GET', 
dataType: 'json',
success: function( data ) {  
  var m = 0;
  for(j in data.rows){
     if ( data.rows[j].media.length >=1 ) { 
       if (data.rows[j].media[0].type == 'Video'){ }
       else {  } 
     }
  }
}

【问题讨论】:

  • 如果我没有出错,在引用 json 对象时长度确实有效。试试data.rows[j].media[0] !=null 而不是data.rows[j].media.length >=1
  • 我按照您的建议尝试了上述两种方法,但它有 TypeError: undefined is not an object (evalating 'data.rows[j].media[0].type')

标签: jquery arrays json ajax get


【解决方案1】:

试试

data.rows[j].media.ToString()!= "[]"

data.rows[j].media.ToString()!= "[ ]"

【讨论】:

    猜你喜欢
    • 2014-03-28
    • 2018-01-15
    • 2019-06-25
    • 2021-11-21
    • 2022-06-29
    • 2015-06-04
    • 2021-02-12
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多