天天看点

WEB前端:ES6(4):数组

Array.from方法用于将两类对象转为真正的数组:
let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};
// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
console.log(arr2);
           
WEB前端:ES6(4):数组
Array.of方法用于将一组值,转换为数组。

let arr = Array.of(3, 11, 8)
console.log(arr);
           
WEB前端:ES6(4):数组
fill方法使用给定值,填充一个数组。
let arr = new Array(5).fill(2);
console.log(arr);
           
WEB前端:ES6(4):数组
数组实例的find方法,用于找出第一个符合条件的数组成员。

[1, 4, -5, 10].find((n) => n < 0)
// -5
上面代码找出数组中第一个小于 0 的成员。

[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10
上面代码中,find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。
           
数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

let arr = [1, 5, 10, 15].findIndex(function(value, index, arr) {
    return value > 9;
})
console.log(arr);
           
WEB前端:ES6(4):数组
Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。

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

let arr = [1, 2, 3].includes(2)
console.log(arr);
           
WEB前端:ES6(4):数组
// for of  遍历数组
let arr3 = [1, 2, 3, 5, 9, 7, 10]

for (let num of arr3) {
    console.log(num);
}
           
WEB前端:ES6(4):数组
Array.prototype.sort() 的排序稳定性 

const arr = [
    'peach',
    'straw',
    'apple',
    'spork'
];

const stableSorting = (s1, s2) => {
    if (s1[0] < s2[0]) return -1;
    return 1;
};

console.log(arr.sort(stableSorting));
           
WEB前端:ES6(4):数组
es6