国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

在JavaScript中操作數(shù)組之map()方法的使用

2024-05-06 16:21:49
字體:
供稿:網(wǎng)友

這篇文章主要介紹了在JavaScript中操作數(shù)組之map()方法的使用,是JS入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下

JavaScript 數(shù)組map()方法創(chuàng)建一個新的數(shù)組使用調(diào)用此數(shù)組中的每個元素上所提供的函數(shù)的結(jié)果。

語法

 

 
  1. array.map(callback[, thisObject]); 

下面是參數(shù)的詳細信息:

callback : 從當(dāng)前的元素函數(shù)產(chǎn)生新的數(shù)組的元素。

thisObject : 對象作為該執(zhí)行回調(diào)時使用

返回值:

返回創(chuàng)建數(shù)組

兼容性:

這種方法是一個JavaScript擴展到ECMA-262標準;因此它可能不存在在標準的其他實現(xiàn)。為了使它工作,你需要添加下面的腳本代碼在頂部:

 

 
  1. if (!Array.prototype.map) 
  2. Array.prototype.map = function(fun /*, thisp*/
  3. var len = this.length; 
  4. if (typeof fun != "function"
  5. throw new TypeError(); 
  6.  
  7. var res = new Array(len); 
  8. var thisp = arguments[1]; 
  9. for (var i = 0; i < len; i++) 
  10. if (i in this
  11. res[i] = fun.call(thisp, this[i], i, this); 
  12.  
  13. return res; 
  14. }; 

例子:

 

 
  1. <html> 
  2. <head> 
  3. <title>JavaScript Array map Method</title> 
  4. </head> 
  5. <body> 
  6. <script type="text/javascript"
  7. if (!Array.prototype.map) 
  8. Array.prototype.map = function(fun /*, thisp*/
  9. var len = this.length; 
  10. if (typeof fun != "function"
  11. throw new TypeError(); 
  12.  
  13. var res = new Array(len); 
  14. var thisp = arguments[1]; 
  15. for (var i = 0; i < len; i++) 
  16. if (i in this
  17. res[i] = fun.call(thisp, this[i], i, this); 
  18.  
  19. return res; 
  20. }; 
  21.  
  22. var numbers = [1, 4, 9]; 
  23. var roots = numbers.map(Math.sqrt); 
  24.  
  25. document.write("roots is : " + roots );  
  26.  
  27. </script> 
  28. </body> 
  29. </html> 

這將產(chǎn)生以下結(jié)果:

 

 
  1. roots is : 1,2,3  

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 麻阳| 德阳市| 凤台县| 万源市| 南雄市| 腾冲县| 女性| 棋牌| 汽车| 千阳县| 涪陵区| 江北区| 台中市| 富平县| 台州市| 白银市| 广东省| 廊坊市| 昌平区| 丰城市| 越西县| 北辰区| 卢龙县| 垦利县| 宜阳县| 涪陵区| 贵州省| 天长市| 伊金霍洛旗| 麻江县| 怀宁县| 沁水县| 衡南县| 土默特左旗| 军事| 秦皇岛市| 德州市| 商河县| 博爱县| 新田县| 宜川县|