標籤:
Array.slice.call(arguments);可以將一個類數組轉化為數組。
(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})();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; };}
js 零零散散的總結。