这是该系列的第28篇笔记!
4,数组实例的entries()、keys()和values()
<!DOCTYPE html>
<html>
<head>
<title>7 数组实例的entries()、keys()和values()</title>
</head>
<body>
<script type="text/javascript">
// 数组实例的entries()、key()和values() --> 用于遍历数组,都能返回一个遍历器对象(15章)
// 可用于for...of循环遍历,3者的区别如下:
// entries() --> 对键值对的遍历
// keys() --> 对键名的遍历
// values() --> 对键值的遍历
for (let index of ['a', 'b'].keys()){
console.log(index);
}
for (let elem of ['a', 'b'].values()){
console.log(elem);
}
for (let [index, elem] of ['a', 'b'].entries()){
console.log(index, elem);
}
// 如果不使用for...of循环,可以手动调用遍历器对象的next方法进行遍历
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, "a"]
console.log(entries.next().value); // [1, "b"]
console.log(entries.next().value); // [2, "c"]
</script>
</body>
</html>
5,数组实例的includes()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>数组实例的includes()</title>
</head>
<body>
<script>
// Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似
// ES6引入该方法
console.log([1, 2, 3].includes(2)); // true
console.log([1, 2, 3].includes(4)); // false
console.log([1, 2, 3].includes(NaN)); // false
// 该方法的第二个参数表示搜索的起始位置,默认为0,如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4, 但数组长度为3),则会重置为从0开始
console.log([1, 2, 3].includes(3, 3)); // false
console.log([1, 2, 3].includes(3, -1)); // true
// 没有该方法之前,我们通常使用数组的indexOf方法检查是否包含某个值
// 这种方式存在2个缺点:a, 不够语义化;b, 其内部使用严格相等运算符(===)进行判断,会导致对NaN的误判
console.log([NaN].indexOf(NaN)); // -1
// includes()方法没有以上的问题
console.log([NaN].includes(NaN)); // true
// 检查当前环境中是否支持该方法:
const contain = ( () =>
Array.prototype.includes? (arr, value) => arr.includes(value): (arr, value) => arr.some(el => el === value)
)();
console.log(contain(['foo', 'bar'], 'zzza')); // false
// Map和Set数据结构的has方法 && includes()
// a, Map的has方法是用来查找键名的
// Map.prototype.has(key);
// WeakMap.prototype.has(key);
// Reflect.has(target, propertyKey);
// b, Set的has方法是用来查找值的
// Set.prototype.has(value);
// WeakSet.prototype.has(value);
</script>
</body>
</html>
让学习“上瘾”,成为更好的自己!!!