Array.prototype.values() - JavaScript Array 对象
Array.prototype.values()
values()
方法返回一个新的Array Iterator
对象,该对象包含数组每个索引的值
语法
arr.values()
返回值
一个新的Array
迭代对象。
示例
使用 for...of
循环进行迭代
let arr = ['w', 'y', 'k', 'o', 'p']; let eArr = arr.values(); // 您的浏览器必须支持 for..of 循环 // 以及 let —— 将变量作用域限定在 for 循环中 for (let letter of eArr) { console.log(letter); }
Array.prototype.values is default implementation of Array.prototype[Symbol.iterator].
Array.prototype.values === Array.prototype[Symbol.iterator]
使用.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 } iteraroe.next().value; // undefined
One-use: the array iterator object is one use or temporary object
example:
var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" for (let letter of iterator) { console.log(letter); } // undefined
reason: When next().done=true
or currentIndex>length
the for..of
loop end. see Iteration protocols.
Value: there is no values stored in the array Iterator object,instead its store the adresse of the array used in creation of it so its depend on the values stored on that array.
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"
if the values in the array changed the array iterator object values change too
TODO: please write about why we need it, use cases.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!