开发者

handling null in json or javascript

开发者 https://www.devze.com 2022-12-13 12:43 出处:网络
Im using an ajax json response to build some html to place in a webpage. Occasionally I\'ll come across an empty value in my json.

Im using an ajax json response to build some html to place in a webpage. Occasionally I'll come across an empty value in my json. This results in an empty object being placed into the html.

I would prefer not to check that each value is not an object, as that doesn't seem efficient. Is there a better way? my code works like this

var firstVar=jsonObj.fristVar;
var secVar=jsonObj.secVar;
var thirdVar=jsonObj.thirdVar;
var fourthVar=jsonObj.fourthVar;
...
var htmlResponse='<div class="'+firstVar+'">'+secVar+'<span class="'+thirdVar+'">开发者_如何学Python;'+fourthVar+'</span>...';
jQuery("body").html(htmlResponse);


If you want to specify default values when they are null, you can just do this:

var firstVar = jsonObj.firstVar || '';
var secVar = jsonObj.secVar || 'No Value';
...

Unrelated to your question, have you looked at an implementation of jQuery templating?


You could use a tertiary operator:

var firstVar = (jsonObj.fristVar != null) ? jsonObj.fristVar : "some default value";
0

精彩评论

暂无评论...
验证码 换一张
取 消