数组

// 数组的扩展
// Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构Set和Map)。
// let arrayLike = {
// '0': 'a',
// '1': 'b',
// '2': 'c',
// length: 3
// };
// let arr = Array.from(arrayLike);
// console.log(arr)//[ 'a', 'b', 'c' ]

// // 只要是部署了Iterator接口的数据结构,Array.from都能将其转为数组
// console.log(Array.from('hello'))
// // ['h', 'e', 'l', 'l', 'o']

// let namesSet = new Set(['a', 'b'])
// Array.from(namesSet) // ['a', 'b']

// Array.from({ length: 3 });
// [ undefined, undefined, undefined ]

// Array.of方法用于将一组值,转换为数组。
// Array.of(3, 11, 8) // [3,11,8]
// Array.of(3) // [3]
// Array.of(3).length // 1

// copyWithin接受三个参数。

// target(必需):从该位置开始替换数据。
// start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
// end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
// [1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

// 数组实例的find()和findIndex()
// find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。
// var f1 = [1, 4, -5, 10].find((n) => n < 0)
// // -5
// // 上面代码找出数组中第一个小于0的成员。
// console.log(f1);
// var f2 =[1, 5, 10, 15].find(function(value, index, arr) {
// return value > 9;
// }) // 10
// console.log(f2)

// [1, 5, 10, 15].findIndex(function(value, index, arr) {
// return value > 9;
// }) // 2

// var arr = [1,2,3];
// arr.fill("b");
// console.log(arr)//[ 'b', 'b', 'b' ]
// // fill方法用于空数组的初始化非常方便。数组中已有的元素,会被全部抹去。
// var arr2 = new Array(3).fill("c");
// console.log(arr2)//[ 'c', 'c', 'c' ]

// entries(),keys()和values()——用于遍历数组
// // 可以用for...of循环进行遍历,唯一的区别是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' ], done: false }//done是什么意思
// console.log(entries.next().value); // [1, 'b']
// console.log(entries.next().value); // [2, 'c']
// console.log(entries.next().value);//undefined

// 表示某个数组是否包含给定的值,includes
// [1, 2, 3].includes(2); // true
// [1, 2, 3].includes(4); // false
// [1, 2, NaN].includes(NaN); // true

// 该方法的第二个参数表示搜索的起始位置,默认为0。
// [1, 2, 3].includes(3, 3); // false
// [1, 2, 3].includes(3, -1); // true

// 另外,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)。

posted @ 2016-10-21 15:28  overAgain  阅读(132)  评论(0编辑  收藏  举报