[JS] ECMAScript 6 - Array : compare with c#

 

扩展运算符(spread)

先复习下 rest 参数。

(1) argument模式,但不够好。

// https://blog.csdn.net/weixin_39723544/article/details/78460470

function
foo(a, b) { var i, rest = []; if (arguments.length > 2) { for (i = 2; i<arguments.length; i++) { rest.push(arguments[i]); } } console.log('a = ' + a); console.log('b = ' + b); console.log(rest); }

(2) 更灵活,但需要在尾部,且不能给默认参数。

function foo(a, b, ...rest) {
    console.log('a = ' + a);
    console.log('b = ' + b);
    console.log(rest);
}

foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]

foo(1);
// 结果:
// a = 1
// b = undefined
// Array []

(3) 三个点(...),它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

该运算符主要用于函数调用,尤其是,数组作为参数时。

function push(array, ...items) {
  array.push(...items);
}

function add(x, y) {
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42

- 参数,任意位置

function f(v, w, x, y, z) { }
const args
= [0, 1]; f(-1, ...args, 2, ...[3]);

-  表达式,先计算出结果

const arr = [
  ...(x > 0 ? ['a'] : []),
  'b',
];

- 空,则无效

[...[], 1]
// [1]

 

 

替代函数的 apply 方法

  由于扩展运算符可以展开数组,所以不再需要apply方法,将数组转为函数的参数了。

  • apply干嘛的? 
obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);

唯一区别是apply接受的是数组参数,call接受的是连续参数。

function add(j, k){
    return j+k;
}

function sub(j, k){
    return j-k;
}

我们在控制台运行:

add(5,3); //8
add.call(sub, 5, 3); //8
add.apply(sub, [5, 3]); //8

sub(5, 3); //2
sub.call(add, 5, 3); //2
sub.apply(add, [5, 3]); //2
  • 不再需要apply方法!

由于扩展运算符可以展开数组,所以不再需要apply方法,将数组转为函数的参数了。

// ES5 的写法
Math.max.apply(null, [14, 3, 77])

// ES6 的写法
Math.max(...[14, 3, 77])  // 看上去比apply舒服一些

// 等同于
Math.max(14, 3, 77);

挽救apply的参数格式之鸡肋。 

// ES5的 写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);  // 因为push的参数格式要求是个鸡肋

// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);    // <---- 看着舒服多了

 

  

扩展运算符的应用 

  • 浅复制
const a1 = [1, 2];
const a2 = a1;
  • 扩展运算符 - 深拷贝
const a1 = [1, 2];
// 写法一
const a2 = [...a1];  // 
// 写法二
const [...a2] = a1;
  • 扩展运算符 - 合并
// ES5的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]

// ES6的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
  • 扩展运算符 - 与解构赋值结合
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]

const [first, ...rest] = [];
first // undefined
rest  // []

const [first, ...rest] = ["foo"];
first  // "foo"
rest   // []
  • 扩展运算符 - 字符串
[...'hello']
// [ "h", "e", "l", "l", "o" ]

* 只要是部署了 Iterator 接口的数据结构,Array.from都能将其转为数组。

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
  • 扩展运算符 - 类数组“转正”
let nodeList = document.querySelectorAll('div');  // nodList类数组,可能其中没有直接使用数组的很多方法
let array = [...nodeList];
  • 扩展运算符 - 具备Iterator 接口的对象【如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错】
let map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

let arr = [...map.keys()]; // [1, 2, 3]

------------------------------------------------------

// 1. 变量go是一个 Generator 函数,执行后返回的是一个遍历器对象
const go = function*(){  
  yield 1;
  yield 2;
  yield 3;
};

[...go()]    // 2. 对这个遍历器对象执行扩展运算符, 就会将内部遍历得到的值,转为一个数组。
// [1, 2, 3]

* 只要是部署了 Iterator 接口的数据结构,Array.from都能将其转为数组。

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
  • 扩展运算符 - 类似数组的对象 【Array.from
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']

* 实际应用中,常见的类似数组的对象是:

// (1) NodeList对象
let ps = document.querySelectorAll('p');
Array.from(ps).filter(p => {
  return p.textContent.length > 100;
});

------------------------------------------------------
// (2) arguments对象 function foo() { var args = Array.from(arguments); // ... }

本质特征只有一点,任何有length属性的对象,都可以通过Array.from方法转为数组,而此时扩展运算符就无法转换。比如:

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

对于还没有部署该方法的浏览器,可以用Array.prototype.slice方法替代。  

 

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

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

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

取出一组 DOM 节点的文本内容

let spans  = document.querySelectorAll('span.name');

// map()
let names1 = Array.prototype.map.call(spans, s => s.textContent);

// Array.from()
let names2 = Array.from(spans, s => s.textContent)  // <---- 看上去简洁

  

例1: 将数组中布尔值为false的成员转为0

Array.from([1, , 2, , 3], (n) => n || 0)
// [1, 0, 2, 0, 3] 

例2: 返回各种数据的类型。

function typesOf () {
  return Array.from(arguments, value => typeof value)
}
typesOf(null, [], NaN)
// ['object', 'object', 'number']

例3: 返回字符串(Unicode 字符)的长度。

function countSymbols(string) {
  return Array.from(string).length;
}

 

 

Array.of()

原来的方式:表达比较混乱。

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]  这里又变成了数组的内容?!

现在的方法:

Array.of基本上可以用来替代Array()new Array()。

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

Array.of方法可以用下面的代码模拟实现。

function ArrayOf(){
  return [].slice.call(arguments);
}

 

 

copyWithin()


/**
* Array.prototype.copyWithin(target, start = 0, end = this.length)
**/
// 将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}

// 将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()

基础:第一个返回值为true的成员

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

高级:参数更多,灵活性更强,比如比较相邻的元素。

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

第二参数:引入另一个对象

function f(v){
  return v > this.age;
}
let person
= {name: 'John', age: 20};

/* person 对应上述f(v)函数中的this */ [
10, 12, 26, 15].find(f, person); // 26

补丁:数组的indexOf方法的不足,无法识别数组的NaN成员。

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

// findIndex方法可以借助Object.is方法做到。 [NaN].findIndex(y => Object.is(NaN, y)) // 0

 

NaN是什么东东?

NaN: Not a Number。代表非数字值的特殊值。该属性用于指示某个值不是数字。可以把 Number 对象设置为该值,来指示其不是数字值。

提示:请使用 isNaN() 全局函数来判断一个值是否是 NaN 值。

方法 parseInt() 和 parseFloat() 在不能解析指定的字符串时就返回这个值。

对于一些常规情况下返回有效数字的函数,也可以采用这种方法,用 Number.NaN 说明它的错误情况。

map方法在调用callback函数时,会自动给它传递三个参数:

(1) 当前正在遍历的元素

(2) 元素索引

(3) 原数组本身

第三个参数parseInt会忽视, 但第二个参数不会,也就是说,parseInt把传过来的索引值当成进制数来使用,从而返回了NaN。

 

 

fill()

// 抹去式填充
['a', 'b', 'c'].fill(7)
// [7, 7, 7]

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

// 或者自定义位置抹去
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']

 

  

entries(),keys() 和 values()

ES6 提供三个新的方法,遍历数组。

  • for...of循环
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"
  • next方法

 

 

includes()

是否包含该元素。

[1, 2, NaN].includes(NaN) // true
[NaN].indexOf(NaN)
// -1  导致了误判

[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)

 

 

数组的空位

一个位置的值等于undefined,依然是有值的。

空位是没有任何值。如下:

第一个数组的 0 号位置是有值的;第二个数组的 0 号位置没有值。

 

ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位。

ES6 则是明确将空位转为undefined

”由于空位的处理规则非常不统一,所以建议避免出现空位。“

Array.from(['a',,'b'])
// [ "a", undefined, "b" ]

[...['a',,'b']]
// [ "a", undefined, "b" ]

[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]

new Array(3).fill('a') // ["a","a","a"]

let arr = [, ,];
for (let i of arr) {
  console.log(1);
}
// 1
// 1

// 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

 

posted @ 2018-04-09 07:17  郝壹贰叁  阅读(200)  评论(0编辑  收藏  举报