A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from below:

TypedArray.from() - JavaScript | MDN

TypedArray.from()

Baseline Widely available

TypedArray.from() メソッドは、配列風オブジェクトや反復可能オブジェクトから新しい型付き配列を生成します。このメソッドは Array.from() とほぼ同じです。

試してみましょう
const uint16 = Int16Array.from("12345");

console.log(uint16);
// Expected output: Int16Array [1, 2, 3, 4, 5]
構文
TypedArray.from(arrayLike, mapFn)
TypedArray.from(arrayLike, mapFn, thisArg)

ここで TypedArray は次のいずれかです。

引数
arrayLike

型付き配列に変換する反復可能または配列風オブジェクトです。

mapFn 省略可

型付き配列の各要素に対して呼び出す関数です。指定された場合、配列に追加するすべての値は最初にこの関数に渡され、代わりに mapFn の返値が型付き配列に追加されます。この関数は以下の引数で呼び出されます。

element

現在処理されている型付き配列の要素です。

index

現在処理されている型付き配列の要素のインデックスです。

thisArg 省略可

mapFn を実行するときに this として使う値です。

返値

新しい TypedArray インスタンスです。

解説

詳しくは Array.from() をご覧ください。

Array.from() と TypedArray.from() の間には微妙な違いがあります(メモ: 下記で言及する this 値は TypedArray.from() が呼び出された this 値であり、 mapFn を呼び出すために用いた thisArg 引数ではありません)。

例 反復可能オブジェクトから (Set)
const s = new Set([1, 2, 3]);
Uint8Array.from(s);
// Uint8Array [ 1, 2, 3 ]
文字列から
Int16Array.from("123");
// Int16Array [ 1, 2, 3 ]
アロー関数と map の使用

アロー関数をマップ関数として使用して要素を操作します。

Float32Array.from([1, 2, 3], (x) => x + x);
// Float32Array [ 2, 4, 6 ]
数列を生成する
Uint8Array.from({ length: 5 }, (v, k) => k);
// Uint8Array [ 0, 1, 2, 3, 4 ]
TypedArray 以外のコンストラクターに対する from() の呼び出し

from() の this 値は TypedArray インスタンスを返すコンストラクターでなければなりません。

function NotArray(len) {
  console.log("NotArray called with length", len);
}

Int8Array.from.call({}, []); // TypeError: #<Object> is not a constructor
Int8Array.from.call(NotArray, []);
// NotArray called with length 0
// TypeError: Method %TypedArray%.from called on incompatible receiver #<NotArray>
function NotArray2(len) {
  console.log("NotArray2 called with length", len);
  return new Uint8Array(len);
}
console.log(Int8Array.from.call(NotArray2, [1, 2, 3]));
// NotArray2 called with length 3
// Uint8Array(3) [ 1, 2, 3 ]
仕様書 ブラウザーの互換性 関連情報

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4