首页 > jquery > jquery测试解析json后数组是否存在

jquery测试解析json后数组是否存在 (jquery test if array exsists after parsing json)

2012-06-29 jqueryjson

问题

我想在onc​​hange事件之后提交我的表单字段。

返回的Json值如下所示:

{ "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } 

我将为此sting添加一个数组,以指定还需要更新的任何其他字段(例如'total'),如下所示:

{ "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error", "toUpdate": [ { "name":"p_total_data1" , "value":"999" } ] } ] } 

所以我只想在toUpdate数组存在时运行更新总脚本。我的问题是如果我使用if语句

if(typeof results.data[0].toUpdate[0].name == 'undefined'){}

要么

if(null != results.data[0].toUpdate[0].name){}

要么

if(results.data[0].toUpdate[0].name.length){}

全部给出错误“results.data [0] .toUpdate [0] .name is undefined”。我该如何测试它是否已定义?

解决方法

results.data[0].toUpdate在尝试访问其属性之前,您需要检查以检查是否存在:

if (results.data[0].toUpdate && results.data[0].toUpdate[0].name){
  // perform the update
}

如果第一个条件评估为假(或任何“假”值),则&&操作员将短路并且根本不会评估第二个条件,从而防止您看到的错误。

问题

I am trying to have my form fields submit after the onchange event.

The Json value returned looks like this:

{ "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } 

I am going to add an array to this sting to specify any other fields (such as 'total') which also need updating, like so:

{ "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error", "toUpdate": [ { "name":"p_total_data1" , "value":"999" } ] } ] } 

So I will only want to run the update total script when the toUpdate array exsists. My issue is if I use an if statement like

if(typeof results.data[0].toUpdate[0].name == 'undefined'){}

or

if(null != results.data[0].toUpdate[0].name){}

or

if(results.data[0].toUpdate[0].name.length){}

All give the error "results.data[0].toUpdate[0].name is undefined". How can I test whether it is defined?

解决方法

You need to check to check for the existence of results.data[0].toUpdate before you attempt to access its properties:

if (results.data[0].toUpdate && results.data[0].toUpdate[0].name){
  // perform the update
}

If the first condition evaluates to false (or any "falsy" value), the && operator will short-circuit and won't evaluate the second condition at all, preventing the error you're seeing.

相似信息