Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Array.from()

Array.from() メソッドは、配列型 (array-like) オブジェクトや反復可能 (iterable) オブジェクトから新しい Array インスタンスを生成します。

ES6 では、クラス構文は、埋め込みとユーザ定義クラスの両方をサブクラスにできます。結果として、Array.from のようなクラス側の静的メソッドは、Array のサブクラスにより "継承" され、Arrayではなく、サブクラスの新しいインスタンスを生成します。

構文

Array.from(arrayLike[, mapFn[, thisArg]])

引数

arrayLike
配列に変換するための array-like オブジェクトまたは iterable オブジェクト
mapFn
任意。配列のすべての要素に対して呼び出される Map 関数。
thisArg
任意。mapFn を実行する時に this として使用する値。

戻り値

新しい Array インスタンス。

説明

Array.from() は、Arraysを生成します:

  • array-like オブジェクト (length プロパティと、インデックス付けされた要素を持つオブジェクト) もしくは
  • iterable オブジェクト (MapSet のような要素を取得するオブジェクト)

Array.from() は任意の引数 mapFn を持ちます。これは、作成した配列 (もしくは、サブクラスオブジェクト) のすべての要素に対して map 関数を実行できます。 より明確に言うと、中間配列を生成しないことを除いて、Array.from(obj, mapFn, thisArg)Array.from(obj).map(mapFn, thisArg) と同じ結果です。中間配列は、適切な型に合うように丸められた値を持つ必要があるため、typed arrays のような配列サブクラスにとっては特に重要です。

from() メソッドの length プロパティは 1 です。

// Array-like object (arguments) to Array
function f() {
  return Array.from(arguments);
}

f(1, 2, 3);
// [1, 2, 3]


// Any iterable object...
// Set
var s = new Set(["foo", window]);
Array.from(s);   
// ["foo", window]


// Map
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]


// String
Array.from("foo");
// ["f", "o", "o"]


// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]


// Generate a sequence of numbers
Array.from({length: 5}, (v, k) => k);
// [0, 1, 2, 3, 4]

ポリフィル

Array.from は ECMA-262 標準の第 6 版に追加されました。他の標準の実装には存在しない可能性があります。次のコードをスクリプトの先頭に記述する事により、Array.from がネイティブでサポートされていない環境でもこれを使用できるようになります。これは、ECMA-262 第 6 版で定められたアルゴリズムと全く同じです。ObjectTypeError はそれぞれオリジナルの値を持ち、callback.callFunction.prototype.call のオリジナルの値として評価されます。加えて、真のiterables ポリフィルできないので、この実装は ECMA-262 第 6 版で定義されている一般的な iterables をサポートしません。

// Production steps of ECMA-262, Edition 6, 22.1.2.1
// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
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 > 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 > 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 > 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 < len… (also steps a - h)
      var kValue;
      while (k < 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;
    };
  }());
}

仕様

仕様 状況 コメント
ECMAScript 2015 (6th Edition, ECMA-262)
Array.from の定義
標準 初期定義
ECMAScript 2017 Draft (ECMA-262)
Array.from の定義
ドラフト  

ブラウザ実装状況

機能 Chrome Firefox (Gecko) Edge Internet Explorer Opera Safari
基本サポート 32 (32) (有) 未サポート (有) 9.0
機能 Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基本サポート 未サポート 未サポート 32.0 (32) 未サポート 未サポート 未サポート

関連情報

ドキュメントのタグと貢献者

 このページの貢献者: YuichiNukiyama, Marsf, shide55
 最終更新者: YuichiNukiyama,