您的位置:首页 > 其它

ES6 之 数组扩展

2018-01-23 17:10 459 查看
本文仅供学习案例记载,资料来源于《ES6标准入门》

Array.from()

Array.of()

数组实例之 copyWithin()

数组实例之 find() ,findIndex()

数组实例之 fill()

数组实例之 entries(),keys(), values()

数组实例之 includes()

数组的空位

数组推导

Array.from()

将两类对象转为真正的数组:类似数组的对象和可遍历的对象(包括 ES6 新增的数据结构 Set 和 Map)。

let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

# 对于还没有部署该方法的浏览器,可以用Array.prototype.slice方法替代。
const toArray = (() =>
Array.from ? Array.from : obj => [].slice.call(obj)
)();


Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

Array.from(arrayLike, x => x * x);  ⇒  Array.from(arrayLike).map(x => x * x);

ps: Array.from(1,2,3, (x) => x * x)       // [1,4,9]

# 将数组中布尔值为false的成员转为0。
Array.from([1, , 2, , 3], (n) => n || 0)  // [1, 0, 2, 0, 3]

# 返回各种数据的类型
function typesOf () {
return Array.from(arguments, value => typeof value)
}
typesOf(null, [], NaN)                   //  ['object', 'object', 'number']


Array.from接受第三个参数,用来绑定this。

Array.from({ length: 2 }, () => 'jack') // ['jack', 'jack']


Array.of()

用于将一组值,转换为数组

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

# Array()的行为有差异
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

ps:Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。

# 对于还没有部署该方法的浏览器,可以用以下方法替代。
function ArrayOf(){
return [].slice.call(arguments);
}


数组实例之 copyWithin()

在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组

Array.prototype.copyWithin(target, start = 0, end = this.length)

target(必需):从该位置开始替换数据。如果为负值,表示倒数。

start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。

end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。

// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)                   // {0: 1, 3: 1, length: 5}

({0:undefined,1:undefined,2:undefined,3: 1,4:undefined,5:undefined,length: 5}).copyWithin(0,3,5);
结果为:
{0:1,1:undefined,2:undefined,3: 1,4:undefined,5:undefined,length: 5};
==>
{0:1,3:1,length:5}

// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);                                        // Int32Array [3, 4, 5, 4, 5]

# 对于没有部署 TypedArray 的 copyWithin 方法的平台 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5]


数组实例之 find() ,findIndex()

find()用于找出第一个符合条件的数组成员

[1, 4, -5, 10].find((n) => n < 0)   //-5

#依次为当前的值、当前的位置和原数组。
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
})                                  // 10

#返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
})                                  // 2


这两个方法都可以接受第二个参数,用来绑定回调函数的this对象

function f(v){
return v > this.age;
}
let person = {name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26

ps:find函数接收了第二个参数person对象,回调函数中的this对象指向person对象


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

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

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

ps: indexOf方法无法识别数组的NaN成员,但是findIndex方法可以借助Object.is方法做到。


数组实例之fill

fill方法使用给定值,填充一个数组。

['a', 'b', 'c'].fill(7)     // [7, 7, 7]

new Array(3).fill(7)        // [7, 7, 7]


fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置

['a', 'b', 'c'].fill(7, 1, 2)   // ['a', 7, 'c']


数组实例之entries(),keys(),values()

用于遍历数组

keys()是对键名的遍历

values()是对键值的遍历

entries()是对键值对的遍历

for (let index of ['a', 'b'].keys()) {
console.log(index);
// 0
// 1
}

for (let elem of ['a', 'b'].values()) {
console.log(elem);
// 'a'
// 'b'
}

for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
// 0 "a"
// 1 "b"
}


如果不使用for…of循环,可以手动调用遍历器对象的next方法,进行遍历。

let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']


数组实例之 includes()

Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true
[NaN].includes(NaN)       // true


该方法的第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。

[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true


检查当前环境是否支持该方法,如果不支持,部署一个简易的替代版本。

const contains = (() =>
Array.prototype.includes
? (arr, value) => arr.includes(value)
: (arr, value) => arr.some(el => el === value)
)();
contains(['foo', 'bar'], 'baz'); // => false


Map 和 Set 数据结构有一个has方法,需要注意与includes区分

Map 结构的has方法,是用来查找键名的,比如Map.prototype.has(key)、WeakMap.prototype.has(key)、Reflect.has(target, propertyKey)。

Set 结构的has方法,是用来查找值的,比如Set.prototype.has(value)、WeakSet.prototype.has(value)。

数组的空位

数组的空位指,数组的某一个位置没有任何值。比如,Array构造函数返回的数组都是空位

Array(3) // [, , ,]
ps:空位不是undefined,一个位置的值等于undefined,依然是有值的。空位是没有任何值,in运算符可以说明这一点。

0 in [undefined, undefined, undefined] // true
0 in [, , ,] // false
ps:第一个数组的 0 号位置是有值的,第二个数组的 0 号位置没有值。


forEach(), filter(), reduce(), every() 和some()都会跳过空位。

map()会跳过空位,但会保留这个值

join()和toString()会将空位视为undefined,而undefined和null会被处理成空字符串。

# forEach方法
[,'a'].forEach((x,i) => console.log(i)); // 1

# filter方法
['a',,'b'].filter(x => true) // ['a','b']

#every方法
[,'a'].every(x => x==='a') // true

# reduce方法
[1,,2].reduce((x,y) => return x+y) // 3

# some方法
[,'a'].some(x => x !== 'a') // false

# map方法
[,'a'].map(x => 1) // [,1]

# join方法
[,'a',undefined,null].join('#') // "#a##"

# toString方法
[,'a',undefined,null].toString() // ",a,,"


# Array.from方法会将数组的空位,转为undefined,也就是说,这个方法不会忽略空位。
Array.from(['a',,'b']) // [ "a", undefined, "b" ]

# 扩展运算符(...)也会将空位转为undefined
[...['a',,'b']]       // [ "a", undefined, "b" ]

# copyWithin()会连空位一起拷贝
[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]

# fill()会将空位视为正常的数组位置。
new Array(3).fill('a')      // ["a","a","a"]

# for...of循环也会遍历空位
let arr = [, ,];
for (let i of arr) {
console.log(1);
}
// 1
// 1
ps:数组arr有两个空位,for...of并没有忽略它们。如果改成map方法遍历,空位是会跳过的


entries()、keys()、values()、find()和findIndex()会将空位处理成undefined。

// entries()
[...[,'a'].entries()] // [[0,undefined], [1,"a"]]

// keys()
[...[,'a'].keys()] // [0,1]

// values()
[...[,'a'].values()] // [undefined,"a"]

// find()
[,'a'].find(x => true) // undefined

// findIndex()
[,'a'].findIndex(x => true) // 0


数组推导

允许直接通过现有数组生成新数组,ES6暂未发布,推迟至ES7

var a1 = [1,2,3,4];
var a2 = [for (i of a1) i * 2];
console.log(a2);/[2,4,6,8]

// for...of后面可以附加if语句,用于设定循环的限制条件
var years = [1954, 1974, 1990, 2006, 2010, 2014];
[for (year of years) if (year > 2000) year ];   //[2006, 2010, 2014]
[for (year of years) if (year > 2000) if (year < 2010) year]; //[2006]

var customers = [
{
name: 'jake',
age: 25,
city: 'New York'
},
{
name: 'rose',
age: 30,
city: 'New York1'
}
]
var results = [
for(c of customers)
if(c.city === 'New York')
{name: c.name, age: c.age}
]
console.log(results);       //{name: 'jake', age: 25}

[for (i of [1,2,3]) i * i ];
==>等价于
[1,2,3].map(function(i) { return i * i});

[for (i of [1,4,2,3,-8]) if (i < 3) i];
==>等价于
[1,4,2,3,-8].map(function(i) { return i < 3});


数组推导需要注意,新数组会立即在内存中生成,这时,假设原数组很大,将非常耗费内存。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: