這篇文章主要介紹了在JavaScript中操作數組之map()方法的使用,是JS入門學習中的基礎知識,需要的朋友可以參考下
JavaScript 數組map()方法創建一個新的數組使用調用此數組中的每個元素上所提供的函數的結果。
語法
- array.map(callback[, thisObject]);
下面是參數的詳細信息:
callback : 從當前的元素函數產生新的數組的元素。
thisObject : 對象作為該執行回調時使用
返回值:
返回創建數組
兼容性:
這種方法是一個JavaScript擴展到ECMA-262標準;因此它可能不存在在標準的其他實現。為了使它工作,你需要添加下面的腳本代碼在頂部:
- if (!Array.prototype.map)
- {
- Array.prototype.map = function(fun /*, thisp*/)
- {
- var len = this.length;
- if (typeof fun != "function")
- throw new TypeError();
- var res = new Array(len);
- var thisp = arguments[1];
- for (var i = 0; i < len; i++)
- {
- if (i in this)
- res[i] = fun.call(thisp, this[i], i, this);
- }
- return res;
- };
- }
例子:
- <html>
- <head>
- <title>JavaScript Array map Method</title>
- </head>
- <body>
- <script type="text/javascript">
- if (!Array.prototype.map)
- {
- Array.prototype.map = function(fun /*, thisp*/)
- {
- var len = this.length;
- if (typeof fun != "function")
- throw new TypeError();
- var res = new Array(len);
- var thisp = arguments[1];
- for (var i = 0; i < len; i++)
- {
- if (i in this)
- res[i] = fun.call(thisp, this[i], i, this);
- }
- return res;
- };
- }
- var numbers = [1, 4, 9];
- var roots = numbers.map(Math.sqrt);
- document.write("roots is : " + roots );
- </script>
- </body>
- </html>
這將產生以下結果:
- roots is : 1,2,3
新聞熱點
疑難解答
圖片精選