第3记:数组需注意的方法篇


一、查找数组内元素的方法

需求:查找数组内元素6是否存在
let arr = [1, 3, 6, 5, 7, 6];

1、indexOf() 和 lastIndexOf()

indexOf()从左往右查找,找到返回索引,找不到返回-1

let index1 = arr.indexOf(6);
console.log(index1);//2

lastIndexOf()从右至左查找,找到返回索引,找不到返回-1

 let index2 = arr.lastIndexOf(6);
 console.log(index2);//5

示例:找出数组 arr 中重复出现过的元素

//输入:[1, 2, 4, 4, 3, 3, 1, 5, 3]
//输出:[1, 4, 3]
  function duplicates(arr) {
    var result = [];
    arr.forEach(elem => {
      if (arr.indexOf(elem) != arr.lastIndexOf(elem) && result.indexOf(elem) == -1) {
        result.push(elem);
      }
//     if (arr.indexOf(elem) != arr.lastIndexOf(elem) && !result.includes(elem)) {
//        result.push(elem);
//      }
    });
    return result;
  }
  let arr = [1, 2, 4, 4, 3, 3, 1, 5, 3]
  console.log(duplicates(arr)) //[1,4,3]

2、includes()

从左往右查找,找到返回true,找不到返回false

let resulr = arr.includes(6);
console.log(resulr);//true

把多个值放在一个数组中,然后调用数组的 includes 方法。

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

3、filter()

也是找出数组 arr 中重复出现过的元素:

function duplicates(arr) {
    return arr.filter( (e,i) =>
     arr.indexOf(e)!==arr.lastIndexOf(e) && arr.indexOf(e)===i);
}

4、find()、findIndex()

find方法:返回找到的元素值,找不到返回undefined

  let value = arr.find(function (currentValue, currentIndex, currentArray) {
    // console.log(currentValue, currentIndex, currentArray);
    if (currentValue === 6) {
      return true;
    }
  });
  console.log(value);

findIndex方法:定制版的indexOf,找到返回索引,找不到返回-1

  let index3 = arr.findIndex(function (currentValue, currentIndex, currentArray) {
    if (currentValue === 6) {
      return true;
    }
  });
  console.log(index3);//2

二、slice() 和 splice()

1.slice(begin,end)

  • 方法返回一个新的数组对象,原始数组不会被改变。

  • 由 begin 和 end 决定的原数组的浅拷贝 (包括 begin,不包括end)

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2, 4));// ["camel", "duck"]
  • begin 参数:如果该参数为负数,则表示从原数组中的倒数第几个元素开始提取(包含 最后一个元素)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(-2));// ["duck", "elephant"]
  • 如果 end 被省略,则 slice 会一直提取到原数组末尾。
    如果 end 大于数组的长度,slice 也会一直提取到原数组末尾
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
console.log(animals.slice(2,9));
// 都是输出:  ["camel", "duck", "elephant"]

console.log(animals.slice(0));
// 输出原数组(浅拷贝一个数组):  ['ant', 'bison', 'camel', 'duck', 'elephant']
  • 如果用slice 创建了一个新数组(数组里面包含对象的引用)。当数组里面的对象引用属性改变了(如:color 属性改变为 purple)。则两个数组中的对应元素都会随之改变

2.splice(start​,deleteCount,item1, item2, … )

  • 此方法会改变原数组。
  • 3个参数:
    1、start:记住数字(正数)是几,就是从第几个后操作

var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");
//从第 2 位后开始删除 0 个元素,插入“drum”
// 运算后的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"]
// 被删除的元素: [], 没有元素被删除

var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myFish.splice(3, 1);
//从第 3 位开始删除 1 个元素
// 运算后的 myFish: ["angel", "clown", "drum", "sturgeon"]
// 被删除的元素: ["mandarin"]

//注意负数情况
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(-2, 1);
//从倒数第 2 位开始删除 1 个元素
// 运算后的 myFish: ["angel", "clown", "sturgeon"]
// 被删除的元素: ["mandarin"]

2、deleteCount:整数,表示要移除的数组元素的个数。
3、最后一个就是往里面加多少个元素


三、sort() 和 reduce()

1、sort()

参数: compareFunction(a, b)


sort 方法可以使用 函数表达式 方便地书写:
function compareNumbers(a, b) {
  return a - b;
}
var numbers = [4, 2, 5, 1, 3];
numbers.sort(compareNumbers);
console.log(numbers);

也可以写成:
var numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b); 
console.log(numbers);

// [1, 2, 3, 4, 5]

注意:如果没有指明 compareFunction ,那么元素会按照转换为的字符串的诸个字符的Unicode位点进行排序。例如 “Banana” 会被排列到 “cherry” 之前。当数字按由小到大排序时,9 出现在 80 之前,但因为(没有指明 compareFunction),比较的数字会先被转换为字符串,所以在Unicode顺序上 “80” 要比 “9” 要靠前。

  let arr = [1, 22, 42, 44, 32, 31, 2, 4, 3]
  arr.sort() //没有参数的情况
  console.log(arr)
  // [1, 2, 22, 3, 31, 32, 4, 42, 44]

2、reduce()

const array1 = [1, 2, 3, 4];
//accumulator:累计器 ; currentValue:数组的元素当前值
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

将二维数组转化为一维

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []
);
// flattened is [0, 1, 2, 3, 4, 5]

四、every和some用法

1、共同点:

1.只能遍历数组
2.符合条件即可跳出循环( 可跳出循环!!! 小心面试坑),返回布尔类型
3.用法相同,接收3个参数:item(当前项),index(当前索引),arr(数组本身)

2、不同点:

every:一项为false就返回false,全为true则返回true
some:一项为true则返回true,全为false则返回false
方便理解:every全true返回true,some一true返回true

  var arr = [1, 2, 3, 4, 5, 6];
//some只要数组里面有一个元素大于3,就返回ture
  console.log(arr.some(item => {
    return item > 3;//遍历到第四个元素(4>3)符合就跳出循环,返回true
  }));
//every要数组里面全部元素大于3,才返回ture
  console.log(arr.every(item => {
    return item > 3; //遍历到第一个元素(1>3)不符合就跳出循环,返回false
  }));
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值