JavaScript奇技淫巧

JavaScript推荐书籍:《JavaScript DOM编程艺术》、《你不知道的JavaScript》、《JavaScript高级程序设计》、《锋利的jQuery》,目前ES6和HTML5是新的技术方向。

JavaScrip较常见的知识点:对象申明、作用域、闭包、this 关键字、函数类、原型类、伪类等面向对象的 JavaScript 中的概念。

 

forEach

// [].forEach(element, index, array)

// forEach函数接受三个参数,按顺序分别是:数组元素,元素的索引,数组本身(如果是一个参数就是数组元素,也就是数组的值)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <script>
 9 
10     if (!Array.prototype.forEach) {
11         Array.prototype.forEach = function (fun /*, thisp*/) {
12             var len = this.length;
13             if (typeof fun != "function")
14                 throw new TypeError();
15 
16             var thisp = arguments[1];
17             for (var i = 0; i < len; i++) {
18                 if (i in this)
19                     fun.call(thisp, this[i], i, this);
20             }
21         };
22     }
23 
24     function printBr(element, index, array) {
25         document.write("<br />[" + index + "] is " + element);
26     }
27 
28     [12, 5, 8, 130, 44].forEach(printBr);
29     //以上代码是为了兼容IE浏览器重写了forEach函数,chrome直接可以直接使用forEach
30 
31     // [].forEach(element, index, array)
32     // forEach函数接受三个参数,按顺序分别是:数组元素,元素的索引,数组本身
33     // (如果是一个参数就是数组元素,也就是数组的值)
34     var arr = [12, 5, 8, 130, 44];
35 
36     function addEach(ele, ind, arra) {
37         console.log(ele);
38         //console.log(arra[ind])
39     }
40 
41     arr.forEach(addEach)
42 </script>
43 </body>
44 </html>
View Code

 

posted @ 2016-12-03 23:58  raykuan  阅读(171)  评论(0编辑  收藏  举报