ES6学习笔记(十五)之数组的扩展3

数组实例

  1. copyWithin( target,start,end):在当前数组内部将指定位置的成员复制到其他位置(会覆盖原有成员),返回当前数组。

参数(数值,若不是则先转为数值):

  • target(必选):从该位置(下标)开始替换数据;
  • start(可选):从该位置(下标)开始读取数据,默认0开始,若为负值表示倒数;
  • end(可选):结束停止数据的位置(下标),默认为数组长度,若为负值表示倒数。
let arr = [0, 8, 5, 6, 4];
let backArr = arr.copyWithin(1, 2, -2);
console.log(backArr); //[ 0, 5, 5, 6, 4 ]
  1. find() 和 findIndex():
    find:返回第一个符合条件的数组成员,若无符合条件的成员则返回undefined;
    findIndex:返回第一个符合条件的数组成员位置,若无符合条件的成员则返回-1;
let arr = [-5, -1, 2, 5];

let backValue = arr.find(v => v < 2);
console.log(backValue); // -5

let backIndex = arr.findIndex(v => v < 2);
console.log(backIndex); // 0

注:

  • 两个方法的参数都是回调函数,并且回调函数可以接受3个参数,依次为值、当前位置和原数组;除了回调函数外,还可接受第二个参数,用来绑定回调函数的this对象。
  • 另外,这两个方法都可以借助Object.is方法找到NaN,弥补了数组的indexOf方法的不足。
let arr2 = [1, NaN, 5];
let nanIndex = arr2.find(v => Object.is(NaN, v));
console.log(nanIndex); //1

console.log(arr2.indexOf(NaN)); // -1
  1. fill():使用给定值填充一个数组。
    参数:填充的值、填充的起始位置和填充的结束位置;
let arr = [1, 5, 8];
// 未给定填充值
console.log(arr.fill()); //[ undefined, undefined, undefined ]
// 指定位置
console.log(arr.fill('a', 1)); //[ 1, 'a', 'a' ]
console.log(arr.fill('a', 0, 1)); //[ 'a', 5, 8 ]
  1. entries()、keys() 和 values():用于遍历数组。
  • entries:遍历键值对;
  • keys:遍历键名;
  • values:遍历键值;
let infoArr = [
    {
        name: '小明',
        age: 18,
        sex: '男',
    },
    {
        name: '小丽',
        age: 15,
        sex: '女',
    },
];

for (let [index, item] of infoArr.entries()) {
    console.log(index);
    console.log(item);
}

for (let index of infoArr.keys()) {
    console.log(index);
}

for (let item of infoArr.values()) {
    console.log(item.name);
}
  1. includes():用来判断数组是否包含给定的值,返回布尔值。

参数:

  • 给定的值;
  • 开始搜索的位置(下标);默认从0开始,若为负值则表示倒数位置开始,若大于数组长度则从0开始;
let arr = [NaN, 5, 8, 'a'];
console.log(arr.includes(5)); //true
console.log(arr.includes(5,1)); //true
console.log(arr.includes(5,5)); //false ,大于数组长度,负数也一样

注:Map和Set数据结构有一个has方法,需注意与includes区分:

  • Map结构的has方法:用来查找键名,例:Map.prototype.has(key);
  • Set结构的has方法:用来查找值,例:Set.prototype.has(value);

数组的空位

注:数组的空位指数组的位置上没有任何值,undefined不是空位,而是这个位置上的值为undefined。

1. ES5对空位的处理(大多数情况下忽略空位)。
  • forEach()、filter()、every() 和 some() 都会跳过空位;
  • map() 虽然会跳过空位,但会保留这个值;
  • join() 和 toString() 会将空位视为undefined,而undefined和null会被处理成空字符串;
2. ES6对空位的处理(明确将空位转为undefined)。
  • Array.from() 和扩展运算符(…) 会将空位转为undefined;
  • entries()、keys()、values()、find() 和 findIndex() 等会将空位处理成undefined;
  • copyWithin() 会连空位一起复制;
  • fill() 会将空位视为正确的数组位置;
  • for…of 循环会遍历空位,但使用map方法遍历会跳过空位;

提示:空位的处理很不统一,所以建议避免出现空位。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值