这是该系列的第27篇笔记!
1,数组实例的copyWithin()
<!DOCTYPE html>
<html>
<head>
<title>4 数组实例的copyWithin()</title>
</head>
<body>
<script type="text/javascript">
// copyWithin()方法: 在当前数组内部将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。即该方法会修改当前数组
// 接收3个参数: a, target(必选) --> 从该位置开始替换数据
// b, start(可选) --> 从该位置开始读取数据,默认为0。如果为负值,表示倒数
// c, end(可选) --> 到该位置前停止读取数据,默认等于数组的长度。如果为负值,表示倒数
// 这3个参数应该都是数值,如果不是,会自动转为数值!!
console.log([1, 2, 3, 4, 5].copyWithin(0, '3')); // [4, 5, 3, 4, 5]
// 【解释】 将从3号位置直到数组结构的成员(4和5)复制到从0号位置开始的位置,结果覆盖了原来的1和2
console.log([1, 1, 1, 1, 2, 2, 3, 3].copyWithin(0, 4, 6)); // [2, 2, 1, 1, 2, 2, 3, 3]
// -2相当于3号位,-1相当于4号位
console.log([1, 2, 3, 4, 5].copyWithin(0, -2, -1)); // [4, 2, 3, 4, 5]
// 将3号位复制到0号位
var aa = {length: 5, 3:1};
console.log(aa);
var arrb = Array.from(aa);
console.log(arrb);
console.log(arrb.length);
console.log([].copyWithin.call({length: 5, 3:1}, 0, 3)); // {0: 1, 3: 1, length: 5}
// 将2号位到数组结束,复制到0号位
var i32a = new Int32Array([1, 2, 3, 4, 5]);
console.log( i32a.copyWithin(0, 2)); // [3, 4, 5, 4, 5]
// 对于没有部署TypeArray的copyWithin方法的平台
// 需要采用下面的写法
console.log([].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4)); // [4, 2, 3, 4, 5]
</script>
</body>
</html>
2,数组实例的find() and findIndex()
// (1)
// find() --> 找出第一个符合条件的数组成员
// 接收一个参数:回调函数,包括当前的值、当前的位置和原数组
// 使用:所有数组成员依次执行该回调函数,直到找出“第一个”返回值为true的成员,然后返回该成员
// 如果没有符合条件的成员,则返回undefined
// console.log([1, 3, 4, 5].find((n) => n < 0)); // undefined
console.log([1, 3, -4, 5].find((n) => n < 0)); // -4
// console.log([12, 3, 4, 15].find((value, index, arr) => value > 10)); // 12 ,而不包括15,因为“第一个”返回true
// findIndex() --> 和find()方法类似,找出第一个符合条件的数组成员的位置
// 如果所有成员都不符合条件,则返回-1
// console.log([12, 3, 4, -3, -5, 23].findIndex((value, index, arr) => value < 0)); // 3
// (2) 这两个方法都可以接受第二个参数,用来绑定回调函数的this对象
// (3) 这两个方法都可以发现"NaN",弥补数组的indexOf方法的不足
// console.log([NaN].indexOf(NaN)); // -1
// console.log([NaN].findIndex((y) => Object.is(NaN, y))); // 0
// indexOf方法无法识别数组的NaN成员,但findIndex方法可以借用Object.is()方法做到
3,数组实例的fill()
// 数组实例的fill() --> 使用给定的值填充一个数组
console.log(['a', 'b', 'c'].fill('aaa'));
var arr = new Array(4).fill(7);
console.log(arr);
// fIll方法用于空数组的初始化非常方便,数组中已有的元素都会被抹去
// fill方法还可以接收第2个和第3个参数,用于指定填充的起始位置和结束位置
var arr1 = ['a', 'b', 'c'].fill('aa', 1, 2);
console.log(arr1);
让学习“上瘾”,成为更好的自己!!!