如何在JSON中使用if语句?

如何在JSON中使用if语句这是代码:……………………………….. ………………………………………….

var config = [ { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 }, { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } ], //define if steps should change automatically autoplay = false, //timeout for the step showtime, //current step of the tour step = 0, //total number of steps total_steps = config.length; 

这是必需的结果,如下所示:

  var config = [ if(page==true) { { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 } } else { { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } } ], //define if steps should change automatically autoplay = false, //timeout for the step showtime, //current step of the tour step = 0, //total number of steps total_steps = config.length; 

实际上这种方式是错误的,并导致JavaScript语法错误。

这是常规JavaScript,而不是JSON。 将if语句移到外面:

 if (page) { var config = [ { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 } ]; } else { var config = [ { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } ]; } 

validationJSON Schema Draft-07 ,JSON现在支持条件数据表示的if...then...else关键字。

 { "type": "integer", "minimum": 1, "maximum": 1000, "if": { "minimum": 100 }, "then": { "multipleOf": 100 }, "else": { "if": { "minimum": 10 }, "then": { "multipleOf": 10 } } } 

或者这个:

  var config = (page == true) ? [ { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 } : { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } ]; 

你也可以这样做(不是说这是最好的方式,但它是另一种方式,在某些情况下可能有用)

 let config = []; if (page) { config.push({ "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }); config.push({ "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 }); } else { config.push({ "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 }); }