aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html
blob: 229b92f5e696f2735632c429c32d521e88cf2d51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
---
title: Array.from()
slug: Web/JavaScript/Reference/Global_Objects/Array/from
tags:
  - Array
  - ECMAScript 2015
  - JavaScript
  - Method
  - Reference
  - polyfill
  - 陣列
translation_of: Web/JavaScript/Reference/Global_Objects/Array/from
---
<div>{{JSRef}}</div>

<p><code><strong>Array.from()</strong></code> 方法會從類陣列(array-like)或是可迭代(iterable)物件建立一個新的 <code>Array</code> 實體。</p>

<div>{{EmbedInteractiveExample("pages/js/array-from.html")}}</div>



<h3 id="參數">參數</h3>

<dl>
 <dt><code>arrayLike</code></dt>
 <dd>將類陣列或可迭代物件轉換成陣列</dd>
 <dt><code>mapFn {{Optional_inline}}</code></dt>
 <dd>Map 函式走訪陣列中的每一個元素。</dd>
 <dt><code>thisArg {{Optional_inline}}</code></dt>
 <dd><code>mapFn</code> 函式執行時的 <code>this</code> 對象。</dd>
</dl>

<h3 id="回傳值">回傳值</h3>

<p>一個新的 {{jsxref("Array")}} 實體。</p>

<h2 id="描述">描述</h2>

<p><code>Array.from()</code> 讓你從這些物件建立陣列:</p>

<ul>
 <li>類陣列(array-like)物件(物件具有 <code>length</code> 屬性以及索引化(indexed)的元素)或</li>
 <li><a href="/zh-TW/docs/Web/JavaScript/Guide/iterable">可迭代物件</a>(物件具有可以讓你利用迭代的方式取得它自己本身的元素,像是 {{jsxref("Map")}}{{jsxref("Set")}})。</li>
</ul>

<p><code>Array.from()</code> 有個可選用的參數 <code>mapFn</code>,它允許你在建立出新的陣列實體之後,可以接著對陣列(或是其子類別物件)中的每一個元素執行 {{jsxref("Array.prototype.map", "map")}} 函式。更清楚地說,<code> Array.from(obj, mapFn, thisArg)</code><code>Array.from(obj).map(mapFn, thisArg)</code> 的結果是一樣的,除非所建立的不是一個可用的中介陣列(intermediate array)。這對於某些陣列的子類別來說就很重要,例如<a href="/zh-TW/docs/Web/JavaScript/Typed_arrays">型別陣列</a>,因為中介陣列必須要把內容值做一番截頭去尾的操作來讓它們變成適合的物件型態。</p>

<p><code>from()</code> 方法的 <code>length</code> 屬性值為 1。</p>

<p>在 ES2015,類別語法允許原生內建的物件以及使用者自定義的物件可以被子類別化(sub-classing);因此,靜態方法像是 <code>Array.from</code>,是「繼承」了 <code>Array</code> 的子類別後,然後建立新的子類別的實體,而不是建立 <code>Array</code> 本身。</p>

<h2 id="範例">範例</h2>

<h3 id="從字串產生陣列">從字串產生陣列</h3>

<pre class="brush: js">Array.from('foo');
// ["f", "o", "o"]</pre>

<h3 id="從集合產生陣列">從集合產生陣列</h3>

<pre class="brush: js">var s = new Set(['foo', window]);
Array.from(s);
// ["foo", window]</pre>

<h3 id="從映射產生陣列">從映射產生陣列</h3>

<pre class="brush: js">var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]</pre>

<h3 id="從類陣列物件(arguments)產生陣列">從類陣列物件(arguments)產生陣列</h3>

<pre class="brush: js">function f() {
  return Array.from(arguments);
}

f(1, 2, 3);

// [1, 2, 3]</pre>

<h3 id="使用箭頭函式及_Array.from">使用箭頭函式及 <code>Array.from</code></h3>

<pre class="brush: js">// 使用箭頭函式作為 map 函式來
// 操作元素
Array.from([1, 2, 3], x =&gt; x + x);
// [2, 4, 6]

// 產生數值序列
// 因為陣列中的每個位置都會被初始化為 `undefined`,
// 下方 `v` 會是 `undefined`
Array.from({length: 5}, (v, i) =&gt; i);
// [0, 1, 2, 3, 4]
</pre>

<h2 id="Polyfill">Polyfill</h2>

<p><code>Array.from</code> 在 ECMA-262 標準第六版(ES2015)被加入;在某些實作可能尚未被支援。你可以將下面的程式碼插入到妳的 script 的最前面,如果你使用的工作環境不具有原生支援 <code>Array.from</code> 的能力。這個演算法根據 ECMA-262 第六版中的規範實現,假定 <code>Object</code><code>TypeError</code> 它們本身已具有值且 <code>callback.call</code> 對應到原本 {{jsxref("Function.prototype.call")}} 的值。除此之外,因為 Polyfill 無法實現真正的迭代,這個實作不支援 ECMA-262 第六版中所定義的泛型迭代。</p>

<pre class="brush: js">// Production steps of ECMA-262, Edition 6, 22.1.2.1
if (!Array.from) {
  Array.from = (function () {
    var toStr = Object.prototype.toString;
    var isCallable = function (fn) {
      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
    };
    var toInteger = function (value) {
      var number = Number(value);
      if (isNaN(number)) { return 0; }
      if (number === 0 || !isFinite(number)) { return number; }
      return (number &gt; 0 ? 1 : -1) * Math.floor(Math.abs(number));
    };
    var maxSafeInteger = Math.pow(2, 53) - 1;
    var toLength = function (value) {
      var len = toInteger(value);
      return Math.min(Math.max(len, 0), maxSafeInteger);
    };

    // The length property of the from method is 1.
    return function from(arrayLike/*, mapFn, thisArg */) {
      // 1. Let C be the this value.
      var C = this;

      // 2. Let items be ToObject(arrayLike).
      var items = Object(arrayLike);

      // 3. ReturnIfAbrupt(items).
      if (arrayLike == null) {
        throw new TypeError('Array.from requires an array-like object - not null or undefined');
      }

      // 4. If mapfn is undefined, then let mapping be false.
      var mapFn = arguments.length &gt; 1 ? arguments[1] : void undefined;
      var T;
      if (typeof mapFn !== 'undefined') {
        // 5. else
        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
        if (!isCallable(mapFn)) {
          throw new TypeError('Array.from: when provided, the second argument must be a function');
        }

        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length &gt; 2) {
          T = arguments[2];
        }
      }

      // 10. Let lenValue be Get(items, "length").
      // 11. Let len be ToLength(lenValue).
      var len = toLength(items.length);

      // 13. If IsConstructor(C) is true, then
      // 13. a. Let A be the result of calling the [[Construct]] internal method
      // of C with an argument list containing the single item len.
      // 14. a. Else, Let A be ArrayCreate(len).
      var A = isCallable(C) ? Object(new C(len)) : new Array(len);

      // 16. Let k be 0.
      var k = 0;
      // 17. Repeat, while k &lt; len… (also steps a - h)
      var kValue;
      while (k &lt; len) {
        kValue = items[k];
        if (mapFn) {
          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
        } else {
          A[k] = kValue;
        }
        k += 1;
      }
      // 18. Let putStatus be Put(A, "length", len, true).
      A.length = len;
      // 20. Return A.
      return A;
    };
  }());
}
</pre>

<h2 id="規格">規格</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">規格</th>
   <th scope="col">狀態</th>
   <th scope="col">備註</th>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>首次定義。</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>

<div>


<p>{{Compat("javascript.builtins.Array.from")}}</p>
</div>

<h2 id="參見">參見</h2>

<ul>
 <li>{{jsxref("Array")}}</li>
 <li>{{jsxref("Array.prototype.map()")}}</li>
 <li>{{jsxref("TypedArray.from()")}}</li>
</ul>