11.1 JavaScript的子集
11.1.1 精华
11.1.2 子集的安全性
11.2 常量和局部变量
<script type="text/javascript"> //关键字let有4种使用方法 //可以作为变量声明,和var一样 //在for或for/in循环中,作为var的代替方案 //在语句块中定义一个新变量并显示指定它的作用域 //定义一个在表达式内部作用域中的变量,这个变量只在表达式内可用 function oddsum(n) { let total = 0, result = []; for(let x = 1; x <= n;x++) { let odd = 2 * x - 1; total += odd; result.push(total); } return result; } //console.log(total); //ReferenceRrror console.log(oddsum(5)); </script>
11.3 解构赋值
<script type="text/javascript"> //解构赋值(destructuring assignment) let [x,y] = [1,2]; //let x=1,y=2 [x,y] = [x + 1,y + 1]; //x = x + 1,y = y + 1 [x,y] = [y,x]; console.log([x,y]); </script>
11.4 迭代
11.4.1 for/each 循环
<script type="text/javascript"> let o = {one: 1,two: 2,three: 3} for(let p in o) { console.log(p); } //for each(let v in o) { // console.log(v); //} </script>
11.4.2 迭代器
<script type="text/javascript"> function counter(start) { let nextValue = Math.round(start); return { next: function() { return nextValue++; } }; } let serialNumberGenerator = counter(1000); let sn1 = serialNumberGenerator.next(); let sn2 = serialNumberGenerator.next(); </script>
11.4.3 生成器
<script type="text/javascript"> //生成器是一个对象,用以表示生成函器函数的当前执行状态 /* function range(min,max) { for(let i = Math.ceil(min);i <= max;i++){ yield i; } } for(let n in range(3,8)) { console.log(n); } */ </script>
11.4.4 数组推导
<script type="text/javascript"> //JavaScript1.7 //数组推导是一种利用另外一个数组或可迭代对象来初始化数组元素的技术 //let evensquares = [x*x for (x in range(0,10)) if (x % 2 === 0)]; //let evensquares = []; //for(x in range(0,10)) { // if(x % 2 === 0) { // evensquares.push(x*x); // } //} //[ expression for ( variable in object ) if ( condition ) ] </script>
11.4.5 生成器表达式
<script type="text/javascript"> //let h = (f(x) for (x in g)); //let lines = eachline(text); //let trimmed = (l.trim() for(l in lines)); //let nonblank = (l for(l in trimmed) if (l.length > 0 && l[0] != ‘#‘)); </script>
11.5 函数简写
<script type="text/javascript"> //对于简单的函数,JavaScript1.8引入一种简写形式:表达式闭包 let succ = function(x) x + 1, yes = function() true, no = function() false; </script>
11.6 多catch从句
<script type="text/javascript"> /* try { throw 1; } catch (e if e instanceof ReferenceError) { } catch(e if e === "quit") { } catch(e if typeof e === "string") { } catch(e) { } finally { } */ </script>
11.7 E4X:ECMAScript for XML
时间: 2024-11-03 22:42:18