js 零零散散的总结。

Array.slice.call(arguments);可以将一个类数组转化为数组。

Array.from() ,[...arr];也可以将一个类数组转化为数组(es6)。

(function() {
    console.log(arguments); //[] 是一个类数组
    console.log(arguments instanceof Array); //false
    console.log(typeof arguments); // object
    var _arguments = Array.prototype.slice.call(arguments);
    console.log(_arguments); // [] 数组
    console.log(_arguments instanceof Array); //true
    console.log(typeof _arguments); //object
    var _arguments1 = Array.from(arguments);
    console.log(_arguments1 instanceof Array); //true
    var _arguments2 = [...arguments];
    console.log(_arguments2 instanceof Array); //true
})();

//Array.from() ,[...arr]这两种是es6的方法。

 扩展运算符背后调用的是遍历器接口(Symbol.iterator),如果一个对象没有部署这个接口,就无法转换。Array.from方法则是还支持类似数组的对象。所谓类似数组的对象,本质特征只有一点,即必须有length属性。因此,任何有length属性的对象,都可以通过Array.from方法转为数组,而此时扩展运算符就无法转换。

array.reduce(callback[, initialValue]);实现二维数组扁平化。

var flatten = matrix.reduce(function (previous, current) {
  return previous.concat(current);
});
console.log(flatten); //[1,2,3,4,5,6]
array.reduce(callback[, initialValue])

callback函数接受4个参数:之前值、当前值、索引值以及数组本身。initialValue参数可选,表示初始值。若指定,则当作最初使用的previous值;如果缺省,则使用数组的第一个元素作为previous初始值,同时current往后排一位,相比有initialValue值少一次迭代。

var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
  return previous + current;
});

console.log(sum); // 10

兼容性封装(针对ie6-8)

if (typeof Array.prototype.reduce != "function") {
  Array.prototype.reduce = function (callback, initialValue ) {
     var previous = initialValue, k = 0, length = this.length;
     if (typeof initialValue === "undefined") {
        previous = this[0];
        k = 1;
     }
     
    if (typeof callback === "function") {
      for (k; k < length; k++) {
         this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
      }
    }
    return previous;
  };
}
原文地址:https://www.cnblogs.com/xiamer/p/5799109.html