Home > Web Front-end > JS Tutorial > body text

JavaScript learning summary [4] JS in-depth

黄舟
Release: 2017-02-09 14:55:27
Original
1330 people have browsed it

1. JS flow control statement

 (1).if judgment

 The if statement executes the corresponding code based on the condition being true.

The if...else statement is the code after if is executed when the specified condition is true, and the code after else is executed when the condition is not true.

If...else Nested statements select one of the corresponding code blocks to execute under multiple conditions.

 The if statement is suitable for any type of data and can handle complex logical relationships.

 (2), switch statement

When there are many choices, switch is more convenient to use than if...else. It has a simple structure and is specially designed for multiple choices, but it can only handle Multiple enumerated logical relationships. This statement can also be completed using if, it depends on personal preference.

How the switch statement works: First create an expression, usually a variable, and then compare the value of the expression with the value of each case in the switch statement. If they match, the statement after the case is executed. If it does not match any case value, the statement after default will be executed. When using a switch statement, break must be used after each case statement to break out of the loop and prevent the next case from running.

var d = new Date().getDay(); //如果今天不是周末,则提示默认消息
 switch (d){     
 case 6:         
 alert("今天是星期六");         
 break;     
 case 0:         
 alert("今天是星期天");         
 break;     
 default:         
 alert("同志尚未努力,革命仍需成功。"); 
 }
Copy after login

When comparing, the switch statement uses congruence instead of equality, so you need to pay special attention when matching strings and numbers.

//使用switch语句将字符串与数字做比较
 //返回:不等于,执行default语句
 var n = '5'; switch(n){     
 case 5:         
 alert('等于,执行case语句');         
 break;     
 default:         
 alert('不等于,执行default语句'); } 
 //使用if语句将字符串与数字做比较
 //返回:等于
 var n = '2'; if(n == 2){     
 alert('等于'); 
 }else{     
 alert('不等于'); 
 } 
 //将case的值改为字符串再做比较
 //返回:等于,执行case语句
 var n = '2'; switch(n){     
 case '2':         
 alert('等于,执行case语句');         
 break;     
 default:         
 alert('不等于,执行default语句'); 
 } 
 
 //使用全等再做比较
 //返回:不等于
 var n = '2'; 
 if(n===2){     
 alert('等于'); }else{     
 alert('不等于'); }
Copy after login

(3), for loop

Many things are not just done once, but need to be done repeatedly. For example, print 10 copies of a document, one copy at a time, and repeat this action until the printing is completed. This kind of thing is done using a for loop. A loop is to repeatedly execute a piece of code with a different value each time.

The following is a small application of a for loop. Assume that there are 1.2.3... 10 RMB with different denominations. Calculate how many RMB there are in total.

var sum = 0; for(var rmb=1; rmb<=10; rmb++){ 
     sum += rmb; } alert(&#39;一共有: &#39; + sum + &#39;元&#39;);    //返回:一共有:55元
Copy after login

(4), while loop

The while loop and the for loop have the same function. As long as the specified condition is true, the loop can be executed until the condition is no longer met.

//使用while循环输出5个数字
 var i = 0;      //第一部分:初始化,给一个初始的值,让i从0循环
 while(i < 5){    //第二部分:条件。成立继续循环,不成立退出
     alert(i);    //第三部分:语句
     i++;     //第四部分:自增
 } //while循环使用比较复杂,使用for循环更简洁。
 //for(初始化;条件;自增){语句}
Copy after login

(5), do...while loop

The principle structure of the do...while loop and the while loop are basically the same, but the loop will check whether the condition is true The code block is executed once before, and if the condition is true, the loop is repeated. There is a slight problem with this loop, because it executes the code first and then determines the conditions. If the conditions are inappropriate, it will enter an infinite loop, causing the browser to crash.

 /*
 语法: do{   执行语句 } while(条件); */
 
 //操作有风险,尝试需谨慎
 //若将循环条件改为:num <= 6 会导致浏览器崩溃  
 var num = 6; do{     document.write("数字:" + num + "<br>");     num -= 1; } while(num > 0);
Copy after login

(6), JS error handling statement

The try...catch statement is used for exception handling. The try statement is used to detect errors in code blocks and indicate the code segments that need to be processed. The catch statement is used to handle errors thrown in the try statement. The try statement is executed first. If an error occurs during operation, the code in the try statement will be skipped and the execution of the statement in the catch will be executed. If no error occurs, the statements in the catch are not executed. Generally, the try...catch statement can be used to deal with foreseeable errors.

try{     
document.write("开始执行try语句" + &#39;<br>&#39;);     
document.write("还没抛出错误" + &#39;<br>&#39;);     
alert(x);        //抛出错误
     alert(&#39;123&#39;);    //没被执行
 } catch(e){     
 document.write("捕捉到错误,开始执行catch语句" + &#39;<br>&#39;);     
 document.write("错误类型: " + e.name + &#39;<br>&#39;);     
 document.write("错误信息: " + e.message);     
 alert(&#39;x&#39;); }
Copy after login

throw statement can be used to create custom errors. The official term is: creating or throwing an exception. Syntax: throw 'Exception object'.​

The throw statement can be used together with the try...catch statement to control the program flow and generate precise error messages.

//输入0到10之间的数字,如果输入错误,会抛出一个错误,catch会捕捉到错误,并显示自定义的错误消息。
 <body>
 <input id="txt" type="text"/>
 <span id="demo" style="font-weight:bold;"></span><br>
 <input type="button" value="检测输入" onclick="error()">
 <script> function error(){     
 try{         
 var x = document.getElementById("txt").value;         
 var y = document.getElementById("demo");         
 y.style.color = &#39;red&#39;;         
 if(x == &#39;&#39;) throw &#39;输入不能为空&#39;;         
 if(isNaN(x)) throw &#39;请输入数字&#39;;         
 var num = [7,8,9];         
 for(var i=0; i<num.length; i++){             
 if(x == num[i]){                 
 throw &#39;该数字已经存在&#39;;             
 }         
 }         
 if(x == 0){             
 throw &#39;输入不能为0&#39;;         
 }         
 else if(x > 10){             
 throw &#39;数字太大了&#39;;         
 }         
 else if(x <= 3){             
 throw &#39;数字太小了&#39;;         
 }         
 else{             
 y.style.color = &#39;green&#39;;             
 y.innerHTML = &#39;OK&#39;;         
 }     
 }     
 catch(e){         
 y.innerHTML = &#39;错误提示:&#39; + e + &#39;!&#39;;     
 } 
 } 
 </script>
 </body>
Copy after login

(7). Break out of the loop

The break statement is used to jump out of the current loop and directly exit the loop to execute the following code, that is, terminate the entire loop without further judgment. The continue statement only jumps out of this loop and continues to execute the following loop, that is, ends this loop, and then determines whether to execute the next loop. return can terminate the execution of the function body and return a value.

for(var i=0; i<6; i++){     if(i == 3) break;    //当i=3时跳出整个循环,不再执行循环
     alert(i);    //返回:0,1,2
 } 
 for(var i=0; i<6; i++){     if(i == 3) continue;    //当i=3时跳出本次循环,继续执行后面循环
     alert(i);    返回:0,1,2,4,5
 }
Copy after login

2、JSON

JSON (JavaScript Object Notation): JS object notation. JSON is mainly used to store and exchange data information, similar to XML, but compared to XML, JSON is easier to read and write, and easier to parse.

 JSON syntax is a subset of JS object representation syntax: data is in key-value pairs separated by commas, curly braces hold objects, and square brackets hold arrays.

The writing format of JSON syntax: "name" : "value", "name" : "value"

The name and value are contained in double quotes and separated by colons. Each piece of data is Comma separated. This is easy to understand, as opposed to name = "value" in JS.

The value of JSON can be: numbers (including integers and decimals), strings (enclosed in double quotes), Boolean values ​​(true or false), objects (enclosed in curly braces), Array (enclosed in square brackets), or null.

JSON is plain text, which is usually used by the server to transfer data to the web page, obtain JSON data from the server, and then use the data in the web page.

 (1), JSON object

var json = {"a": 12, "b": "abc", "c":[1,2,3]}; //返回第一项的值:
 alert(json.a); 
 //修改第二项的值
 alert(json.b = "xyz"); 
 //返回第三项数组中第一项的值
 alert(json.c[0]);
Copy after login

 (2), JSON and array

Similar points:

Both can return an item through subscript value. You can use loops. Although JSON does not have a length attribute and cannot use a for loop, you can use a for...in loop to complete the same action as a for loop.

Arrays can also use for...in loops, but it is better to use for loops. The for...in loop iterates over the properties of the object, not the elements of the array.

difference:

  JSON 的下标是字符串,数组的下标为数字。JSON 没有 length 属性,数组有该属性。

var arr = [12,5,7]; var json = {"a":12,"b":5,"c":7}; 
 alert(arr[0]);      //返回:12
 alert(json["a"]);    //返回:12
 
 alert(arr.length);    //返回:3
 alert(json.length);   //返回:undefined
 
 //数组for循环
 for(var i=0; i<arr.length; i++){     alert(&#39;第&#39; + (i+1) + &#39;个数据是:&#39; + arr[i]); } alert(typeof i);    //返回:number
 
 //数组使用for...in循环
 for(var i in arr){     alert(&#39;第&#39; + (i+1) + &#39;个数据是:&#39; + arr[i]); } alert(typeof i);    //返回:string
 
 //JSON使用for...in循环
 for(var i in json){     alert(&#39;第&#39; + i + &#39;个数据是:&#39; + json[i]); }
Copy after login

  (3)、JSON 数组对象

<body>
 <p>
 姓 名: <span id="fname"></span><br> 
 性 别: <span id="gender"></span><br>
 员工号: <span id="num"></span><br> 
 修改姓名: <span id="lname"></span><br> 
 </p> 
 <script> var staff = [     {"name" : "小明", "sex" : "男", "id" : 1}, 
     {"name" : "小白", "sex" : "男", "id" : 2}, 
     {"name" : "小红", "sex" : "女", "id" : 3} ]; 
     var x = document.getElementById("fname"); 
     var y = document.getElementById("gender"); 
     var z = document.getElementById("num"); 
     var n = document.getElementById("lname"); //访问对象数组中第一项的值:
 x.innerHTML = staff[0].name; y.innerHTML = staff[0].sex; z.innerHTML = staff[0].id; 
 //修改数据:
 n.innerHTML = staff[1].name = &#39;大白&#39;; </script>
 </body>
Copy after login

  (4)、JSON 字符串对象

var str = &#39;{"name":"小明", "sex":"男", "age":21}&#39;;
var toObj = JSON.parse(str);  //JSON字符串转换为JSON对象alert(toObj.name);
alert(typeof toObj);    //返回:object
var json = {"name":"小红", "sex":"女", "age":18};
var toStr = JSON.stringify(json);  //JSON对象转换为JSON字符串
alert(toStr);    //返回字符串alert(json.age);
alert(typeof toStr);    //返回:string
Copy after login

(5)、JSON 应用

  当需要表示一组数据时,JSON 不但能够提高可读性,而且还可以减少复杂性。JSON 能够表示多个值,每个值又可包含多个值,例如要表示一个用户列表信息,就可以将所有信息存储在一个变量中,分成多项,每项中又可分成多个条目,每个条目中记录一个用户的信息。

var userName = {     
"first": [{         
"name": "路飞",         
"sex": "男",         
"tel": "aaa"    
 },  {         
 "name": "索罗",         
 "sex": "男",         
 "tel": "bbb"     
 }, {         
 "name": "娜美",         
 "sex": "女",         
 "tel": "ccc"     }], 
     "second": [{         
     "name": "卡卡西",         
     "sex": "男",         
     "tel": "ddd"     
     }, {         
     "name": "鸣人",         
     "sex": "男",         
     "tel": "fff"     
     }, {         
     "name": "佐助",         
     "sex": "男",         
     "tel": "eee"     
     }, {         
     "name": "皱田",         
     "sex": "女",         
     "tel": "sss"     
     }], 
     "third": [{         
     "name": "小明",         
     "sex": "男",         
     "tel": "xxx"     
     },{         
     "name": "小红",         
     "sex": "女",         
     "tel": "zzz"     
     }] 
     }; 
 //获取用户的信息:
 alert(userName.first[1].name + &#39; \n &#39; + userName.first[1].sex + &#39;\n &#39;+ userName.first[1].tel); 
 alert(userName.second[3].name + &#39; \n &#39; + userName.second[3].sex +&#39; \n &#39;+ userName.second[3].tel); 
 alert(userName.third[0].name + &#39; \n &#39; + userName.third[0].sex + &#39; \n &#39;+ userName.third[0].tel);
Copy after login

说到 JSON,就不得不提一下 JSONP。JSONP (JSON with Padding) 是 JSON 的一种 "使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。可用于解决主流浏览器的跨域数据访问的问题。为什么我们从不同的域(网站)访问数据需要一个特殊的技术 (JSONP) 呢?这是因为同源策略。同源策略,它是由 Netscape 提出的一个著名的安全策略,现在所有支持 JavaScript 的浏览器都会使用这个策略。由于该策略,一般来说位于 server1 的 demo.com 的网页无法与不是 server1 的 demo.com 的网页的服务器沟通,而 HTML 的

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!