数组方法总结

摘自
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/values


// 增删改查数组
1.// push() 从后面增加 返回的是这个数组的长度 会改变原数组
const animals = [1,3,3];
const count = animals.push('cows');
console.log(count);
// expected output: 4
2. // unshift() 方法将一个或多个元素添加到数组的开头 返回的是这个数组的长度 会改变原数组
3.// shift() 从数组中删除第一个元素 返回的是这个数组的长度 会改变原数组
const array2 = [1, 2, 3];
const firstElement = array2.shift();
console.log(array2);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
4. // pop 从数组中删除最后一个元素 返回的是删除的这个元素 会改变原数组
5. // splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。会改变原数组
 //语法: // array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
//  从第2为开始删除0个元素 也就是说将drum插入数组中
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");
// 运算后的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"]
// 被删除的元素: [], 没有元素被删除
6. // slice()返回是一个新的数组对象,不会改变原数组 相当于根据位置浅拷贝这个数组
const array = [1,2,3,4]
const arrayTest = array.slice(2,3) // 从索引的第二个截取到第三个但是不包括第三个
console.log(arrayTest)
// 数组遍历
1.// entries
// Array.entries()
// 方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
const array3 = ['a', 'b', 'c'];
const iterator1 = array3.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "a"]
2. // every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值
// 只有数组中的每一个都符合条件 才会返回true
const isBelowThreshold = (currentValue) => currentValue < 40;
const array4 = [1, 30, 39, 29, 10, 13];
console.log(array4.every(isBelowThreshold));
// expected output: true
3. // some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试 返回的是一个boolean
// 数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false。
4. // 填充数组
// fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引
// arr.fill(value[, start[, end]])
// value 填充数组的值 start从哪个索引开始 end到哪个索引终止 不包括索引终止
const array5 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array5.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array5.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array5.fill(6));
// expected output: [6, 6, 6, 6]
5.// 展平数组
// flat() 返回一个新数组
var newArray = arr.flat([depth])
// depth 可选
// 指定要提取嵌套数组的结构深度,默认值为 1
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// flat() 方法会移除数组中的空项:
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]
6.// 连接数组
// concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
const array7 = ['a', 'b', 'c'];
const array8 = ['d', 'e', 'f'];
const array9 = array7.concat(array8);
console.log(array9);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
7.// filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
/**
 * Array filters items based on search criteria (query)
 */
const filterItems = (query) => {
  return fruits.filter((el) =>
    el.toLowerCase().indexOf(query.toLowerCase()) > -1
  );
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
8.// find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
  return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
9.// findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
// 以下示例查找数组中素数的元素的索引(如果不存在素数,则返回-1)
function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}
console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
10. // forEach() 方法对数组的每个元素执行一次给定的函数。
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
11.// map() 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。返回的是一个新数组
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
//forEach, find, filter, findIndex, map(callback[, thisArg]) callback 中接收3个参数 element index array thisArg 可选
// 可选参数。当执行回调函数 callback 时,用作 this 的值。
// element 当前遍历到的元素 index可选 当前遍历到的索引 array可选 数组本身
12. // reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。[支持IE]
// reducer 函数接收4个参数:
// Accumulator (acc) (累计器)
// Current Value (cur) (当前值)
// Current Index (idx) (当前索引)
// Source Array (src) (源数组)
// reduceRight() 方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。
(1)// 累加
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// 和为 6
(2)// 累加数组对象中的值
var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    ,initialValue
);
console.log(sum) // logs 6
// 展开数组
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( acc, cur ) => acc.concat(cur),
  []
 );
(3)// 按顺序执行promise
/**
 * Runs promises from array of functions that can return promises
 * in chained manner
 *
 * @param {array} arr - promise arr
 * @return {Object} promise object
 */
 function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  );
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5);
  });
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2);
  });
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3;
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4);
  });
}

const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10)
  .then(console.log);   // 1200
13.// flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。
// 返回值是一个新的数组,其中每个元素都是回调函数的结果,并且结构深度 depth 值为1。
let arr1 = ["it's Sunny in", "", "California"];
arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]
arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]
14.// Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。返回一个新的数组
// Array.from(arrayLike[, mapFn[, thisArg]])
// arrayLike
// 想要转换成数组的伪数组对象或可迭代对象。
// mapFn 可选
// 如果指定了该参数,新数组中的每个元素会执行该回调函数。
// thisArg 可选
// 可选参数,执行回调函数 mapFn 时 this 对象。
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
// 从类数组对象(arguments)生成数组
function f() {
  return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
// 数组去重合并
function combine(){
  let arr = [].concat.apply([], arguments);  //没有去重复的新数组
  return Array.from(new Set(arr));
}
var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n)); 
13.//includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
// arr.includes(valueToFind[, fromIndex])
// valueToFind
// 需要查找的元素值。
// fromIndex 可选
// 从fromIndex 索引处开始查找 valueToFind。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜 (即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0。
// includes() 方法有意设计为通用方法。它不要求this值是数组对象,所以它可以被用于其他类型的对象 (比如类数组对象)。下面的例子展示了 在函数的 arguments 对象上调用的 includes() 方法。
(function() {
  console.log([].includes.call(arguments, 'a')); // true
  console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');
15.// indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1 返回值首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1
// lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
console.log([2,3,4].indexOf(3, -1));
// expected output: -1
16. //Array.isArray() 用于确定传递的值是否是一个 Array。
17. //join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符
18. // keys() 方法返回一个包含数组中每个索引键的对象。
19. // values() 方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值
20. // reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]
21. // sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的
// 对象可以按照某个属性排序:
var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic' },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort(function (a, b) {
  return (a.value - b.value)
});

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});
22.// toString() 返回一个字符串,表示指定的数组及其元素
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值