最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Default Values for JSON in javascript - Stack Overflow

programmeradmin4浏览0评论

In the code:

slider.init({
 foo: "bar"
});

var slider={
 init:function(data){
 }
}

If I use data.foo, I will get "bar".

Supposing I have an optional variable called fish which can be included in the JSON variable. If I reference data.fish, I will be told that it is undefined or an error will be thrown or something. Is there a way that I can assign a default value to fish so that when I request data.fish, even though it is not set in the parameter, I will get a default value?

In the code:

slider.init({
 foo: "bar"
});

var slider={
 init:function(data){
 }
}

If I use data.foo, I will get "bar".

Supposing I have an optional variable called fish which can be included in the JSON variable. If I reference data.fish, I will be told that it is undefined or an error will be thrown or something. Is there a way that I can assign a default value to fish so that when I request data.fish, even though it is not set in the parameter, I will get a default value?

Share Improve this question edited Apr 20, 2015 at 13:27 jcuenod asked Sep 6, 2009 at 19:24 jcuenodjcuenod 58.4k15 gold badges69 silver badges103 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

You can use the or operator to assign default values in case the aren't defined, for example:

var slider = {
 init:function(data){
   var fish = data.fish || "default value";
 }
}

Or you can make an "extend" function, to merge two objects, similar to the jQuery extend function:

function extend (obj1, obj2) { 
  var result = obj1, val;
  for (val in obj2) {
    if (obj2.hasOwnProperty(val)) {
      result[val] = obj2[val];
    }
  }
return result;
}

var defaults = {val1: 1, val3: 3, fish: 'fish'};
extend(defaults, {val2: 2}); // returns Object val1=1 val3=3 fish=fish val2=2
发布评论

评论列表(0)

  1. 暂无评论