JavaScript基本知识——学习笔记之数组api总结

概述

自从IE6、火狐2、谷歌1浏览器之后的版本都支持es3语法,而ES5在2009年发布后,所有现代浏览器都完美的支持ES5语法,之后ES6于2015年发布,ES7于2016年发布,各版本之间有些新的特性,导致在编写代码时注意兼容性就成了前端开发的必修课,为了用es6/7语法就需要用babel转义。

数组的兼容性

ES3支持Array对象的方法属性

es3支持的api有toString()、toLocaleString()、concat()、join()、pop()、push()、reverse()、shift()、slice()、sort()、splice()、unshift(),如下:
在这里插入图片描述
具体api的用法可以参考MDN数组语法

ES5支持Array对象的方法属性

浏览器对es5的支持程度如下:
在这里插入图片描述
针对数组es5新增的特性有:indexOf, forEach, map , filter, isArray,reduce,some等等。

ES6支持Array对象的方法属性

es6新的语法像let、const、对象的结构等都适用于数组,还有箭头函数等等。对数组的新增api如下:

  1. Array.from()方法从一个类似数组或可迭代对象中创建一个新的数组实例。参数为:(arrayLike[, mapFn[, thisArg]]),这里的伪数组可以是:数组、字符串、Map、Set、arguments、对象等等。
  2. Array.prototype[@@iterator]默认返回与values()值相同的值,arr[Symbol.iterator] ()
  3. Array.of()方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型
  4. Array.prototype.copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,而不修改其大小。
  5. Array.prototype.find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
  6. Array.prototype.findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
  7. Array.prototype.fill()方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
  8. Array.prototype.includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

数组方法是否改变原数组或返回新数组

一、改变原数组的方法

Array.prototype.pop()
Array.prototype.push()
Array.prototype.reverse()
Array.prototype.shift()
Array.prototype.sort()
Array.prototype.splice()
Array.prototype.unshift()

二、返回新数组的方法

Array.of()
Array.prototype.concat()
Array.prototype.copyWithin()
Array.prototype.fill()
Array.prototype.filter()
Array.prototype.map()
Array.prototype.slice()

三、其他

Array.prototype.entries()
Array.prototype.every()
Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.forEach()
Array.prototype.includes()
Array.prototype.indexOf()
Array.prototype.join()
Array.prototype.keys()
Array.prototype.lastIndexOf()
Array.prototype.reduce()
Array.prototype.reduceRight()
Array.prototype.some()
Array.prototype.toLocaleString()
Array.prototype.toSource()
Array.prototype.toString()
Array.prototype.values()
Array.prototype[@@iterator]()

数组方法的使用场景

一、伪数组转化为数组

var arrayLike = new Set([1,2,3]);
//es5语法
console.log(Array.prototype.slice.call(arrayLike)); //[1,2,3]
//es6语法
console.log(Array.from(arrayLike)); //[1,2,3]
console.log([...arrayLike]); //[1,2,3]

二、数组的去重

  1. 利用Set对象去重,Array.from()或对象解构转为数组(es6实现)
var a = [1, 2, 2, 3, 4, 4, 5]
console.log(Array.from(new Set(a)));  //[1, 2, 3, 4, 5]
console.log([...new Set(a)]);         //[1, 2, 3, 4, 5]
  1. 利用call/apply方法(es5实现)
var a = [1, 2, 2, 3, 4, 4, 5]
console.log(Array.protoType.slice.call(new Set(a)));  //[1, 2, 3, 4, 5]

猜你喜欢

转载自blog.csdn.net/qq_29510269/article/details/88600999