在JavaScript中運算元組之map()方法的使用_基礎知識

來源:互聯網
上載者:User

 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 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.