JavaScript不清不楚之entries、keys、values
程序员文章站
2023-12-25 15:01:33
...
Array.prototype.entries
以下代码均来自:MDN
- entries方法返回一个新的Array Iterator对象,每个元素项是包含数组中每个索引的键/值对
- IE系列不支持
var arr = ["a", "b", "c"];
var iter = arr.entries();
var res = [];
for(var i=0; i< arr.length; i++){ // 注意,是length+1,比数组的长度大
var tem = iter.next(); // 每次迭代时更新next
console.log(tem.done); // 遍历迭代器结束done才是true
res[i]=tem.value;
}
console.log(res); //[[0, "a"], [1, "b"], [2, "c"]]
var arr = ["a", "b", "c"];
var iterator = arr.entries();
for (let e of iterator) {
console.log(e);
}
// [0, "a"]
// [1, "b"]
// [2, "c"]
Array.prototype.keys
- entries方法返回一个新的Array Iterator对象,每个元素项是数组中每个索引的键
- IE系列不支持
//next的用法
var arr = ["a", "b", "c"];
var iterator = arr.keys();
console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
//索引迭代器会包含那些没有对应元素的索引
var arr = ["a", , "c"];
var denseKeys = [...arr.keys()];
console.log(denseKeys); // [0, 1, 2]
Array.prototype.values
- entries方法返回一个新的Array Iterator对象,每个元素项是数组中每个索引的值
- IE系列不支持
let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();
console.log(eArr.next().value); // w
console.log(eArr.next().value); // y
console.log(eArr.next().value); // k
console.log(eArr.next().value); // o
console.log(eArr.next().value); // p
//for of
let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();
// 您的浏览器必须支持 for..of 循环
for (let letter of eArr) {
console.log(letter);
}