## 6.4 JavaScript使用案例 ### 6.4.1 JavaScript逻辑判断语法案例 #### 例子1: //判断字符串长度: ~~~javaScript var name = "西门吹雪"; document.write(name.length); ~~~ //判断是否包含字符串: ``` var name = "西门吹雪"; if(name.indexOf("西门") > -1){ document.write("包含西门"); }else{ document.write("不包含西门"); } ``` #### 例子2: ``` var age = 18 if(age < 18){ document.write("你还未成年,不能观看"); }else{ document.write("欢迎观看"); } ``` #### 例子3: ```js var age = 18; if (age > 0 && age <= 6) { document.write("你还是一个孩子"); } else if (age > 6 && age <= 17) { document.write("你是一个少年"); } else if (age > 17 && age <= 40) { document.write("你是一个青年"); } else if (age > 40 && age <= 65) { document.write("你是一个中年"); } else { document.write("你已步入老年"); } ``` #### 例子4: ``` var age = 19; if(age < 6 || age > 18){ document.write("你不是一个少年"); }else{ document.write("你是一个少年"); } ``` #### 例子5: ``` var name = "张三"; if(name!= "张三"){ document.write("你不是张三"); }else{ document.write("你是张三"); } var name = "张三"; if(!(name == "张三")){ document.write("你不是张三"); }else{ document.write("你是张三"); } ``` #### 例子6: ``` var age = 17; if((age > 0 && age < 18) || (age > 65)){ document.write("欢迎光临你可以免费游园"); }else{ document.write("请先购票"); } ``` #### 例子7: ``` var age = 18; var man = age>=18?"你已经成年":"你还未成年"; document.write(man); ``` #### 例子8: ``` var name = "刘德华"; switch(name) { case "刘德华": document.write("这个人长的超帅的!"); break; case "梁朝伟": document.write("这个人有一双迷人的眼睛!"); break; case "吴彦祖": document.write("超级大帅锅"); break; case "杨洋": document.write("小鲜肉"); break; default: document.write("此人未被列入帅哥名单"); } ``` #### 例子9: 循环遍历数组 ``` var nameList=["张三","李四","王五","赵六"]; for (var i in nameList) { document.write(nameList[i] + "<br>"); } ``` #### 例子10: 判断王五是否存在 ``` var name = "王五"; var nameList = ["张三", "李四", "王五", "赵六"]; var flag = false; for (var i in nameList) { if (nameList[i] == name) { flag = true; break; } } if (flag) { document.write("这群人中包含王五"); } else { document.write("这群人中不包含王五"); } ``` ### 6.4.2 ruyi.ai模版输入参数与输出参数使用案例 **ruyi.ai模板输入参数in案例** 在线调试案例对应的JS ``` sys.template.javascript.v2= var name=sys.in.name; var age=sys.in.age; var result = ""; if(age < 18){ result = name + " 你还未成年,不能观看"; }else{ result = name + "欢迎观看"; } return result; ``` **ruyi.ai模板输出参数out案例** 输出参数out使用模版 ``` sys.template.javascript.v2= var code =sys.out.result; return code; ``` **说明** ``` 'sys '做为系统变量 ,请慎用。 ``` 天气查询输出参数out真实案例 + ①天气查询接口的输出json为: ![](https://box.kancloud.cn/8e9fc08e9920946d7832398fd965be84_472x715.jpg) + ②当用户问“今天天气怎样?”时,我们想让机器人做出如下回答: ![](https://box.kancloud.cn/689060c59f03d2418b49e8e8255b7b32_348x406.jpg) 使用到的接口out的值如图所示: ![](https://box.kancloud.cn/9e78916afe813ed6736ce84615f98dfc_503x722.jpg) + ③这条JS应当编写如下 ``` sys.template.javascript.v2= var max = sys.out.day_weather.tmp.max; var min = sys.out.day_weather.tmp.min; var qlty = sys.out.aqi.city.qlty; var result = ""; if (date != 'null') { if (max != 'null' && min != 'null') { result = '温差是' + (max - min); } if (qlty != 'null') { result = result + '<br/>空气质量' + qlty; } } return result; ```