关于数组的一切

数组的创建

var arr = []; //创建一个空数组  语法糖
var arr2 = new Array(); //使用构造函数创建一个空数组

关联数组和索引数组

  • 索引数组:使用索引值对数组的元素进行编号
  • 关联数组:使用字符串作为数组的索引
    注:关联数组不计算长度(length:0) 无法使用for语句遍历,可以用for...in遍历
// 关联数组
var arr = []
arr['name'] = '张三'
arr['age'] = 20
arr['sex'] = '男'

Array.from()

  • 语法:Array.from(arrayLike[, mapFn[, thisArg]])
  • 描述:可以通过以下方式来创建数组对象
    • 伪数组对象(拥有一个 length 属性和若干索引属性的任意对象)
    • 可迭代对象(可以获取对象中的元素,如 Map和 Set 等)
  • 参数:
    • arrayLike:想要转换成数组的伪数组对象或可迭代对象
    • mapFn:如果指定了该参数,新数组中的每个元素会执行该回调函数。
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

Array.isArray()

  • 语法: Array.isArray(obj)
  • 描述:判断是否是一个数组
  • 参数:需要检测的值。
  • 返回值:如果值是 Array,则为true; 否则为false
Array.isArray([1, 2, 3]);  
// true
Array.isArray({foo: 123}); 
// false
Array.isArray("foobar");   
// false
Array.isArray(undefined);  
// false

Array.prototype.push()

  • 语法: arr.push(element1,…,elementN)
  • 描述:该方法用于在数组的尾部添加 1到多个元素
  • 参数:element 需要添加到数组尾部的元素(any)
  • 返回值:返回添加内容后的新长度
  • tip: 直接修改原数组
var sports = ["soccer", "baseball"];
var total = sports.push("football", "swimming");

console.log(sports); 
// ["soccer", "baseball", "football", "swimming"]

console.log(total);  
// 4

Array.prototype.pop()

  • 语法: arr.pop()
  • 描述: 该方法用于删除数组中的最后一个元素
  • 返回值:返回被删除的元素,如果数组为空,返回undefined
  • tip:直接修改原数组
let myFish = ["angel", "clown", "mandarin", "surgeon"];
let popped = myFish.pop();

console.log(myFish); 
// ["angel", "clown", "mandarin"]

console.log(popped); 
// surgeon

Array.prototype.shift()

  • 语法: arr.shift()
  • 描述: 该方法用于删除并返回数组中的第一个元素,并将后面的元素向前移一位,将数组的长度-1
  • 返回值:返回被删除的元素
  • tip:该方法直接修改原数组
let myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

console.log('调用 shift 之前: ' + myFish);
// "调用 shift 之前: angel,clown,mandarin,surgeon"

var shifted = myFish.shift(); 

console.log('调用 shift 之后: ' + myFish); 
// "调用 shift 之后: clown,mandarin,surgeon" 

console.log('被删除的元素: ' + shifted); 
// "被删除的元素: angel"

Array.prototype.unshift()

  • 语法: arr.unshift(value[,value2,…valueN])
  • 描述: 该方法用于在数组的头部插入一条或多条数据, 将参数的值依次插入输入,将数组原来的值向后移动
  • 参数: value 要插入到数组头部的值
  • 返回值:返回添加内容后的新长度
  • tip: 该方法直接操作原数组
let arr = [4,5,6];
arr.unshift(1,2,3);
console.log(arr); // [1, 2, 3, 4, 5, 6]

arr = [4,5,6]; // 重置数组
arr.unshift(1);
arr.unshift(2);
arr.unshift(3);
console.log(arr); // [3, 2, 1, 4, 5, 6]

Array.prototype.concat()

  • 语法: arr.concat(value1,[…,valueN]); //语法中出现中括号表示这个参数可选
  • 参数: value 需要添加到新数组的元素
  • 描述: 该方法用于将参数依次添加到数组的尾部,并返回一个新数组
  • 返回值:添加元素后的新数组
  • tip:该方法不修改原数组
// 数组扁平化
var alpha = ['a', 'b', 'c'];
var numeric = [1, 2, 3];

alpha.concat(numeric);
// result in ['a', 'b', 'c', 1, 2, 3]

Array.prototype.toString()

  • 语法: arr.toString()
  • 描述: 将数组内所有的元素都进行toString() 然后用,连接
  • 返回值: 拼接好的字符串
const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

Array.prototype.join()

  • 语法:arr.join(substring)
  • 描述: 该方法用于将数组内所有的元素都进行toString()操作,并进行拼接。如果一个元素为 undefined 或 null,它会被转换为空字符串。
  • 参数: substring 用于拼接字符串的连接符号
  • 返回值: 新的字符串,包含了数组所有元素toString的结果,默认情况使用英文逗号拼接
var a = ['Wind', 'Rain', 'Fire'];
var myVar1 = a.join();      // myVar1的值变为"Wind,Rain,Fire"
var myVar2 = a.join(', ');  // myVar2的值变为"Wind, Rain, Fire"
var myVar3 = a.join(' + '); // myVar3的值变为"Wind + Rain + Fire"
var myVar4 = a.join('');    // myVar4的值变为"WindRainFire"

Array.prototype.reverse()

  • 语法:arr.reverse()
  • 描述:该方法颠倒数组中的所有元素(修改的是排列顺序)
  • 返回值:颠倒后的数组
  • tip: 直接修改原数组
const a = [1, 2, 3];
console.log(a); // [1, 2, 3]
a.reverse(); 
console.log(a); // [3, 2, 1]

Array.prototype.sort()

  • 语法:arr.sort([compareFunction])
  • 描述:通过比较元素Unicode码对数组进行排序
  • 返回值:排序后的数组
  • tip: 直接修改原数组
var numbers = [4, 2, 5, 1, 3]
numbers.sort((a, b) => a - b) //升序
console.log(numbers)

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

Array.prototype.splice()

  • 语法: arr.splice(start[deleteCount[,val,…]])
  • 描述: 可以用于删除指定索引值的数组元素、可以用于数组的元素替换、可以在指定的索引位置插入新的元素 并将之前的元素向后移动
  • 参数:
    • start 开始索引
    • deleteCount 要删除的数量
      • 如果没有这个参数 删除到数组结尾
      • 如果 deleteCount 大于 start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位)
      • 如果 deleteCount 是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素(val有值)
    • val 要插入到start位置的元素
  • 返回值: 返回被删除的数组片段(Array),如果没有删除元素,则返回空数组。
  • tip:该方法直接操作原数组
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// 插入新元素
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// 替换元素
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

console.log(months.splice(3, 1));
// expected output: ["April"]
// 删除元素
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "May"]

Array.prototype.slice()

  • 语法: arr.slice(start[,end])
  • 描述: slice函数用于截取数组指定索引的片段
  • 参数:
    • start 开始的索引
    • end 结束索引
      • 如果没有end参数 则从start开始到数组结尾结束,从而实现数组的浅拷贝
      • 如果 end 大于数组的长度,slice 也会一直提取到原数组末尾
      • end 允许是负数 -1表示最后1个 -2表示倒数第二个 依次类推
  • 返回值:一个含有被截取元素的新数组,如果没有截取到,返回一个空数组
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

Array.prototype.indexOf()

  • 语法: arr.indexOf(value[,start])
  • 描述: 该方法用于检索数组中的value值,如果找到 则返回下标 没有找到 返回-1
  • 参数:
    • value 在数组中需要检索的值
    • start 开始索引
  • 返回值: 返回首个找到元素所对应的索引值 否则返回 -1
var array = [2, 5, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
// 数组去重
var arr = [123, 11, 723, 123, 123, 11, 71, 62];
var result = [];
for (var i = 0; i < arr.length; i++) { 
  if (arr.indexOf(result, i) === -1) {
     result.push(arr[i]);
  }
}
console.log(result);

Array.prototype.forEach()

  • 语法: arr.forEach(callback)
  • 描述: 该函数用于遍历数组 并将数组的每一个元素和索引值传入到回调函数中
  • 回调参数:
    • value 数组中的每一个元素
    • index 元素所对应的索引值
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

Array.prototype.filter()

  • 语法: arr.filter(callback)
  • 描述: 该方法用于过滤数组
  • callback参数:
    • value 数组内的每一个元素
    • index 元素所对应的索引值
    • array 数组本身
    • thisArg 执行 callback 时,用于 this 的值。
  • 返回值:一个新的、过滤后的数组,如果没有任何数组元素通过,则返回空数组。
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]fd -+

Array.prototype.map()

  • 语法: arr.map(callback)
  • 描述: 函数map用于遍历并操作数组元素
  • callback参数:
    • value 数组内的每一个元素
    • index 元素所对应的索引值
    • array 数组本身
    • thisArg 执行 callback 时,用于 this 的值。
  • 返回值: 新的数组
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]

筛选一个数组中对象中的某一属性成一个新数组

var arr = [
      {
        id: 1,
        name: '张三'
      }, {
        id: 2,
        name: '李四'
      }, {
        id: 3,
        name: '王二麻子'
      }
    ]
 var newArr = arr.map(item=>item.id)
 // newArr:[1, 2, 3]

Array.prototype.reduce()

  • 语法: arr.reduce(callback)
  • callback 参数
    • pre 上一次调用回调时返回的累积值
    • next 数组中正在处理的元素
    • index 数组中正在处理的当前元素的索引
    • array 数组本身
    • initialValue 作为第一次调用 callback函数时的第一个参数的值
  • 返回值:函数累计处理的结果
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
});

callback 被调用四次,每次调用的参数和返回值如下表:

callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call011[0, 1, 2, 3, 4]1
second call122[0, 1, 2, 3, 4]3
third call333[0, 1, 2, 3, 4]6
fourth call644[0, 1, 2, 3, 4]10
// 对数组中的所有值求和
var numbers = [3, 5, 7, 2]
var sum = numbers.reduce((x, y) => x + y)
console.log(sum) // returns 17

Array.prototype.includes()

  • 语法: arr.includes(valueToFind[, fromIndex])
  • 描述: 判断一个数组是否包含一个指定的值
  • 参数:
    • valueToFind 需要查找的元素值
    • fromIndex 开始查找的索引值
  • 返回值:true/false
[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true

Array.prototype.every()

  • 语法: arr.every(callback)
  • 描述: 使用一个逻辑表达式 检测数组中的每一个元素,如果全部通过检测 则返回true
  • callback参数:
    • element 当前元素
    • index 元素所对应的索引值
    • array 数组本身
    • thisArg 执行 callback 时,用于 this 的值
  • 返回值:true/false
  • tip:若收到一个空数组,此方法在一切情况下都会返回 true

Array.prototype.some()

  • 语法: arr.some(callback);
  • 描述: 使用一个逻辑表达式 检测数组中的每一个元素,如果有一个通过检测 则返回true
  • callback参数:
    • element 当前元素
    • index 元素所对应的索引值
    • array 数组本身
    • thisArg 执行 callback 时,用于 this 的值
  • 返回值:true/false
  • tip:如果用一个空数组进行测试,在任何情况下它返回的都是false
[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true

Array.prototype.find()

  • 语法: arr.find(callback[, thisArg])
  • 描述: 用于找出第一个符合条件的数组成员
  • callback参数:
    • element 当前元素
    • index 元素所对应的索引值
    • array 数组本身
    • thisArg 执行 callback 时,用于 this 的值
  • 返回值:数组中第一个满足所提供测试函数的元素的值,否则返回 undefined。
[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10

Array.prototype.findIndex()

  • 语法: arr.findIndex(callback[, thisArg])
  • 描述: 用于找出第一个符合条件的数组成员
  • callback参数:
    • element 当前元素
    • index 元素所对应的索引值
    • array 数组本身
    • thisArg 执行 callback 时,用于 this 的值
  • 返回值:数组中通过提供测试函数的第一个元素的索引。否则,返回-1
[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

另外,这两个方法都可以发现NaN,弥补了数组的indexOf方法的不足

[NaN].indexOf(NaN)
// -1

[NaN].find(y => Object.is(NaN, y))
// NaN

[NaN].findIndex(y => Object.is(NaN, y))
// 0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值