evantianx / Bloooooooog

Place to record what I thought and learned
0 stars 0 forks source link

JavaScript 中的 Array #37

Open evantianx opened 7 years ago

evantianx commented 7 years ago

参考文章:

【深度长文】JavaScript 数组所有 API 全解密

evantianx commented 7 years ago

Array 构造器

构造一个数组通常有两种方法,较为普遍的是对象字面量方法:

// 使用 Array 构造器
const a = Array(3)

// 使用对象字面量
const b = []
b.length = 3

我们在使用构造器的时候并没有添加关键字 new,但仍然创建了一个数组实例,这是为什么呢?

规范上写到:

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

Array 构造器语法如下:

evantianx commented 7 years ago

ES6中新增的构造函数方法

Array.of

用于将参数依次转换为数组中的一项,然后返回新数组,不论该参数为何种类型。

Array.of(1) // [1]
Array(1) // [undefined]

所以如果单单是为了用数组包裹元素,建议使用Array.of()

对于不支持 Array.of 的浏览器,可以用下面的 Polyfill 代替:

if (!Array.of) {
  Array = function() {
    return Array.prototype.slice.call(arguements);
  };
}

slice method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The arguments inside a function is an example of an 'array-like object'.

function list() {
  return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]

Array.from

能将一个拥有迭代器的对象(String,Set,Map,arguments等)转换为数组。不改变原对象,返回一个新数组。

语法: 三个参数。第一个为要转换的对象,必选;第二个为加工函数,可选;第三个为this,可选;

一旦传入加工函数,则在函数内部必须明确返回值,否则数组成员将均为 undefined。

// 使用 Array.from() 输出从 0 到指定数字的数组
Array.from({length: 10}, (v, i) => i)  
evantianx commented 7 years ago

Array.isArray

在 ES5 提供该方法之前,用来判断数组的唯一可靠的方法恐怕只有这个了:

// 也是 Array.isArray 的 Polyfill
if (!Array.isArray){
  Array.isArray = function(arg){
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

遍历方法

evantianx commented 7 years ago

数组原型方法

改变原数组的方法