Array.prototype.concat()
- 合并一個或多個數組;
- 不會覆蓋原數組結構斋泄;
- 多個數組的合并杯瞻,存在相同值不會被覆蓋;
- 數組合并的是對象炫掐,那么對象會被加入到數組中去(見示例abk變量)
- 數組合并的是字符串或者數字魁莉,會將字符串或數字加入到數組中去(見示例 abc變量)
//代碼
let a = ["a","b","c"];
let b = ["c","d","e"];
let c = [1,2,3];
let ab = a.concat(b);
let ac = a.concat(c);
let abc = ["a","b"].concat("c");
let abk = ["a","b"].concat({k:"123"});
//結果
// a = ["a","b","c"]
// ab = ["a", "b", "c", "c", "d", "e"]
// ac = ["a", "b", "c", 1, 2, 3]
// abc = ["a","b","c"]
// abk = ["a","b",{k:"123"}]
Array.prototype.reduce()
- 數據累加
- 數組迭代、遞歸
- 刪除數組中的某個元素
示例1
let sum = [0, 1, 2, 3].reduce(function(result, item) {
return result + item;
}, 10);
console.log(sum);
//結果
//16
示例2
// 刪除 對象中 id=2的數據
let sum = [{id:1,val:"1"},{id:2,value:"2"},{id:3,value:"3"}].reduce(function(result, item) {
if(item.id!=2){
return result.concat(item);
}else{
return result;
}
}, []);
console.log(sum);
//結果
[{id:1,val:"1"},{id:3,value:"3"}]
reduce接收兩個參數
- callback回調函數募胃,接受四個參數
- 上次回調函數的結果(或初始值(initialValue) 旗唁,即reduce方法的第二個參數)
- 當前正在進行的元素
- 正在進行中的元素的數組索引,如果沒有初始值痹束,則回調從1開始執(zhí)行
- 調用 reduce 的數組
- initialValue 可選項检疫,其值用于第一次調用 callback 的第一個參數。
應用其他場景
// 數組扁平化
let arr = [1,[3,4],[5,6],[[7,8,9]]];
function flatten(arrs){
let newarr = []
newarr =
arrs.reduce(function(result,item){
if( Array.isArray(item) ){
return result.concat( flatten(item) );
}else{
return result.concat(item);
}
},[]);
return newarr
}
var a = flatten(arr);
Polyfill(墊片)
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, 'reduce', {
value: function(callback /*, initialValue*/) {
if (this === null) {
throw new TypeError( 'Array.prototype.reduce ' +
'called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback +
' is not a function');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
k++;
}
// 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
value = o[k++];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// ? accumulator, kValue, k, O ?).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
}
});
}
Array.prototype.slice(start , end)
- 提取數組祷嘶,不修改原數組
- 淺拷貝(一維數組是對象或數組屎媳,改變提取出的數組它的對象原數組也會被改變,如示例二)
slice( start , end )
- 參數 start (可選)论巍,原數組索引位置
- 參數 end (可選)烛谊,原數組第n個的位置
- slice( 2, 3 ) 提取原數組索引為2的,直到原數組從左到右的第3個值
- 如果數組中有 對象引用(不是實際的對象)环壤,那么改變該對象引用晒来,相應的新數組與原數組的對象引用也會隨之改變(如示例二)
示例一
let arr = ["a","b","c","d","e","f","g"];
let r1 = arr.slice();
let r2 = arr.slice(2, 5);
let r3 = arr.slice(3);
// r1 結果為 ["a","b","c","d","e","f","g"];
// r2 結果為 ["c","d","e"]
// r3 結果為 ["d",······]
示例二
// myHonda 是對象引用
var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
var myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
var newCar = myCar.slice(0, 2);
// 改變myHonda對象的color屬性.
myHonda.color = 'purple';
// myCar 及 newCar對應的color屬性會跟著改變
經典場景
// 直接執(zhí)行 Array.prototype.slice()將會得到結果為一個空數組
// 將 類似數組對象(Array-like)轉換為真正的數組
// 如果是obj是對象引用則報錯,即不是數組對象無法使用該方法
var obj = {0:"a",1:"c",2:"e",length:3};
// 原型寫法
Array.prototype.slice.call(obj);
// 簡寫形式
[].slice.call(obj);
代碼兼容
/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
*/
(function () {
'use strict';
var _slice = Array.prototype.slice;
try {
// Can't be used with DOM elements in IE < 9
_slice.call(document.documentElement);
} catch (e) { // Fails in IE < 9
// This will work for genuine arrays, array-like objects,
// NamedNodeMap (attributes, entities, notations),
// NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
// and will not fail on other DOM objects (as do DOM elements in IE < 9)
Array.prototype.slice = function (begin, end) {
// IE < 9 gets unhappy with an undefined end argument
end = (typeof end !== 'undefined') ? end : this.length;
// For native Array objects, we use the native slice function
if (Object.prototype.toString.call(this) === '[object Array]'){
return _slice.call(this, begin, end);
}
// For array like object we handle it ourselves.
var i, cloned = [],
size, len = this.length;
// Handle negative value for "begin"
var start = begin || 0;
start = (start >= 0) ? start: len + start;
// Handle negative value for "end"
var upTo = (end) ? end : len;
if (end < 0) {
upTo = len + end;
}
// Actual expected size of the slice
size = upTo - start;
if (size > 0) {
cloned = new Array(size);
if (this.charAt) {
for (i = 0; i < size; i++) {
cloned[i] = this.charAt(start + i);
}
} else {
for (i = 0; i < size; i++) {
cloned[i] = this[start + i];
}
}
}
return cloned;
};
}
}());
Array.prototype.toString()
- 返回一個字符串郑现,表示指定的數組及其元素湃崩。
- 該方法等同于數組調用了join方法
- 該方法無參數
示例一
let arr = ["abc","efg","myName"];
arr.toString(); // 方法一
Array.prototype.toString.call(arr); //方法二
arr.join(","); //方法三
//以上三種方法效果一致---------------------
示例二
// 多維數組(數組中沒有對象)與一維數組
let arr = ["abc",["a","c"],"1","2"];
// 結果
// abc,a,c,1,2
// -------------------------------------
// 多維數組中存在 鍵值對象的情況
var list = ["abc",["a","c"],"1",{"key":"val"}];
// 結果
// abc,a,c,1,[object Object]
Array.prototype.find(callback[, thisArg])
-
find()
方法返回數組中滿足提供的測試函數的第一個元素的值荧降。否則返回undefined
。 -
findeIndex()
方法攒读,它返回數組中找到的元素的索引朵诫,而不是其值。 - find 方法不會改變數組薄扁。
- 在第一次調用 callback 函數時會確定元素的索引范圍剪返,即調用后添加了數組不會被訪問到,以及回調函數中未被訪問的數組被提前刪除邓梅,該元素扔然能被訪問到
參數
-
callback 數組每一項回調函數脱盲,擁有參數:
- element 當前遍歷到的元素。
- index 當前遍歷到的索引日缨。
- array 數組本身钱反。
thisArg( 可選 )— 指定 callback 的 this 參數。
如果提供了 thisArg 參數匣距,那么它將作為每次 callback 函數執(zhí)行時的上下文對象面哥,否則上下文對象為 undefined
返回
- 當某個元素通過 callback 的檢驗時,返回數組中的這個元素的值毅待,否則返回undefined
Polyfill(墊片)
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, ? kValue, k, O ?)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}