Array.prototype.values()
values()
メソッドは、配列の各インデックスの値を含む新しい Array Iterator
オブジェクトを返します。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
arr.values()
返値
新しい Array
iterator オブジェクトです。
例
for...of ループを用いた反復処理
var arr = ['a', 'b', 'c', 'd', 'e'];
var iterator = arr.values();
for (let letter of iterator) {
console.log(letter);
} //"a" "b" "c" "d" "e"
Array.prototype.values は Array.prototype[Symbol.iterator] の既定の実装です。
Array.prototype.values === Array.prototype[Symbol.iterator] //true
.next() を使用した反復処理
var arr = ['a', 'b', 'c', 'd', 'e'];
var iterator = arr.values();
iterator.next(); // Object { value: "a", done: false }
iterator.next().value; // "b"
iterator.next()["value"]; // "c"
iterator.next(); // Object { value: "d", done: false }
iterator.next(); // Object { value: "e", done: false }
iterator.next(); // Object { value: undefined, done: true }
iteraror.next().value; // undefined
一度だけの使用: 配列の反復子オブジェクトは一度だけの使用またはテンポラリオブジェクトです
例:
var arr = ['a', 'b', 'c', 'd', 'e'];
var iterator = arr.values();
for (let letter of iterator) {
console.log(letter);
} //"a" "b" "c" "d" "e"
for (let letter of iterator) {
console.log(letter);
} // undefined
理由: next().done=true
または currentIndex>length
が for..of
の終了条件だからです。反復処理プロトコルを参照して下さい。
値: 配列の反復子オブジェクトには値が格納されません。その代わりに、その作成に使用された配列のアドレスが格納されるので、その配列に格納されている値に依存します。
var arr = ['a', 'b', 'c', 'd', 'e'];
var iterator = arr.values();
console.log(iterator); // Array Iterator { }
iterator.next().value; // "a"
arr[1]='n';
iterator.next().value; // "n"
配列内の値が変化した場合は、配列の反復子オブジェクトの値も変化します。
TODO: please write about why we need it, use cases.
仕様書
ブラウザーの互換性
BCD tables only load in the browser