Javascript有很多數(shù)組的方法,有的人有W3C的API,還可以去MDN上去找,但是我覺得API上說的不全,MDN上又太多。。其實(shí)常用的就那幾個(gè),很多都可以用那幾個(gè)方法解出來。
很多方法中有兼容性的,在使用的時(shí)候,把兼容代碼復(fù)制粘貼即可。
先貼上來數(shù)組和字符串的方法的比較,我在學(xué)習(xí)的時(shí)候也是會(huì)混。所以做了小總結(jié)。之后就是數(shù)組方法和一些實(shí)例。如果有側(cè)邊欄就好了,看得就比較清楚。
數(shù)組 字符串
slice | slice substring 截取需要開始和結(jié)束index的
splice | substr 截取需要開始index和截取長度的
concat | concat 都是連接,一個(gè)是連接數(shù)組,一個(gè)是連接字符串
indexOf | indexOf 搜索元素在不在里面,返回index值或者-1
join | split 這就是兩個(gè)反義詞啊,相互轉(zhuǎn)化的利器
- 截取方法中,字符串有三種方法slice / substring / substr ,數(shù)組方法有兩個(gè)slice / splice
其中字符串的slice 和 substring 是要開始和結(jié)束的索引,substr 是要開始索引和長度
數(shù)組的slice是要開始和結(jié)束索引,但是splice是要開始索引和長度- 搜索元素方法中,數(shù)組和字符串都有indexOf方法,但是字符串多出來兩種方法charAt和charCodeAt
其中indexOf是返回索引,charAt是返回索引對(duì)應(yīng)的值,charCodeAt是返回對(duì)應(yīng)值的ASCII碼值。- 數(shù)組的遍歷有4中方法,map,every,foreach,some,filter
其中foreach開始就停不下來,全部遍歷。every遍歷一個(gè)就判斷一下,true就繼續(xù)遍歷下一個(gè),false就跳出。map就是邊遍歷邊運(yùn)算。some返回的是布爾值,符合就是true,不符合就是false。filter返回的是符合元素組成的數(shù)組。- 增加數(shù)組元素,前面unshift,后面push
移除數(shù)組元素,前面shift,后面pop- 數(shù)組和字符串都有concat方法,各自連接各自的,是數(shù)組就連接到數(shù)組,字符串就連接成字符串
- 比較重要的兩個(gè)就是數(shù)組和字符串之間的轉(zhuǎn)化的兩個(gè)方法
join是數(shù)組轉(zhuǎn)字符串,split是字符串轉(zhuǎn)數(shù)組
數(shù)組
Array.prototype
Array.prototype 屬性表示構(gòu)造函數(shù)的原型,并允許您向所有Array對(duì)象添加新的屬性和方法。
/*
如果JavaScript本身不提供 first() 方法,
添加一個(gè)返回?cái)?shù)組的第一個(gè)元素的新方法。
*/
if(!Array.prototype.first) {
Array.prototype.first = function() {
return this[0];
}
}
Array.prototype本身也是一個(gè) Array
Array.isArray(Array.prototype);
// true
//屬性
Array.prototype.constructor
//所有的數(shù)組實(shí)例都繼承了這個(gè)屬性,它的值就是 Array,表明了所有的數(shù)組都是由 Array 構(gòu)造出來的。
Array.prototype.length
//上面說了,因?yàn)?Array.prototype 也是個(gè)數(shù)組,所以它也有 length 屬性,這個(gè)值為 0,因?yàn)樗莻€(gè)空數(shù)組。
判斷是不是數(shù)組的方式
Array.isArray( );
Array.isArray( obj );
靜態(tài)方法,是數(shù)組構(gòu)造函數(shù)的方法
-
obj是需要檢測(cè)的值,如果是數(shù)組,返回true,否則返回false
// 下面的函數(shù)調(diào)用都返回 true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); // 鮮為人知的事實(shí):其實(shí) Array.prototype 也是一個(gè)數(shù)組。 Array.isArray(Array.prototype); // 下面的函數(shù)調(diào)用都返回 false Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray({ __proto__: Array.prototype }); -
存在兼容問題(IE8及以下不支持)
//Polyfill //假如不存在 Array.isArray(),則在其他代碼之前運(yùn)行下面的代碼將創(chuàng)建該方法。 if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }?
(Object.prototype)toString.call(arr) -> [object Array]
Object.prototype.toString.call([]) -> [ object Array]
- 轉(zhuǎn)化成字符串是"[object Array]",可以作為判斷條件。
- Object.prototype.toString.call(obj).slice(8,-1); -> ==='Array'
- ({}).toString.call(function(){}).slice(8,-1); -> ==='Function'
- slice截取,前面的是從第八個(gè)開始,截取到倒數(shù)的第二個(gè)。
instanceof
對(duì)象 instanceof 數(shù)據(jù)類型
console.log(obj instanceof Array);
-
(不嚴(yán)謹(jǐn))多個(gè)頁面進(jìn)行判斷,會(huì)有問題
//iframe /*B頁面嵌套到A頁面中,每個(gè)頁面都有一個(gè)top屬性,top屬性一直都指向A頁面的window,所以在A頁面定義的函數(shù)fn,暴露在B頁面的全局環(huán)境中,在B頁面中也可以調(diào)用。*/ top.fn(); //(就是調(diào)用頁面A的fn函數(shù)) //那么問題來了: B頁面: top.fn([]); A頁面: function fn(arr){ console.log(arr instanceof Array); } //此時(shí)會(huì)成為false //要直接訪問A頁面,訪問B頁面會(huì)報(bào)錯(cuò),因?yàn)橹淮蜷_的頁面的top指向自己的window,此時(shí)調(diào)用了沒有定義的函數(shù)。 //防止被嵌套:if( top != window){ top.location.href = ‘inner-B.html’;} //跳轉(zhuǎn)到自己的地址
數(shù)組長度
數(shù)組的length屬性總是比數(shù)組中定義的最后一個(gè)元素的下標(biāo)大一,表示數(shù)組中元素的個(gè)數(shù)。
-
數(shù)組的length屬性在創(chuàng)建數(shù)組的時(shí)候初始化,在添加新元素的時(shí)候數(shù)組長度改變
//如果函數(shù)中沒有參數(shù),a為空數(shù)組 var a = new Array(); // a.length 被初始化為 0 //如果函數(shù)參數(shù)是一個(gè),參數(shù)表示函數(shù)的長度 var b = new Array(10); // b.length 被初始化為 10 //如果函數(shù)參數(shù)是兩個(gè)及以上,參數(shù)表示數(shù)組內(nèi)容 var c = new Array("one", "two", "three"); // c.length 被初始化為 3 c[3] = "four"; // c.length 被更新為 4 c[10] = "blastoff"; // c.length 變?yōu)?11 -
設(shè)置屬性length的值可以改變數(shù)組的大小,設(shè)置值小則被從后截?cái)?,設(shè)置值大則剩下的值都為undefined
var a = new Array("one", "two", "three"); a.length = 2; //["one", "two"] a.length = 5; //["one", "two", undefined × 3]?
遍歷數(shù)組
map
var new_array = array.map (function(value,index,array){ },thisArg);
遍歷數(shù)組,能夠?qū)?shù)組轉(zhuǎn)化為一個(gè)新的數(shù)組,新數(shù)組的值由map方法回調(diào)函數(shù)的返回值決定。
回調(diào)函數(shù)的第一個(gè)參數(shù)是數(shù)組的值,第二個(gè)參數(shù)是索引,第三個(gè)參數(shù)是被調(diào)用的數(shù)組。thisArg可選,執(zhí)行 callback函數(shù)時(shí) 使用的this值。
如果 thisArg 參數(shù)有值,則每次 callback 函數(shù)被調(diào)用的時(shí)候,this都會(huì)指向thisArg參數(shù)上的這個(gè)對(duì)象。如果省略了 thisArg參數(shù),或者賦值為null或undefined,則 this 指向全局對(duì)象 。
返回值是新的數(shù)組
var arrNew = arr.map(function(value,index){
console.log(‘索引是’+index+”,內(nèi)容是:”+value+);
})
let numbers = [1, 5, 10, 15];
let roots = numbers.map(function(x) {
return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
-
求數(shù)組中每個(gè)元素的平方根
var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); /* roots的值為[1, 2, 3], numbers的值仍為[1, 4, 9] */
-
使用 map 重新格式化數(shù)組中的對(duì)象
var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]; var reformattedArray = kvArray.map(function(obj){ //obj指的是每一個(gè)數(shù)組元素,是一個(gè)對(duì)象 var rObj = {}; rObj[obj.key] = obj.value; return rObj; }); // reformattedArray is now [{1:10}, {2:20}, {3:30}], // kvArray is still [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]
-
將數(shù)組中的單詞轉(zhuǎn)換成對(duì)應(yīng)的復(fù)數(shù)形式
var words = ["foot", "goose", "moose", "kangaroo"]; //定義函數(shù) function fuzzyPlural(single) { //所有的o變成e var result = single.replace(/o/g, 'e'); if( single === 'kangaroo'){ result += 'se'; } return result; } //遍歷每一個(gè)元素 console.log(words.map(fuzzyPlural)); // ["feet", "geese", "meese", "kangareese"]
-
如何讓一個(gè)string使用map方法獲取字符串中每個(gè)字符所對(duì)應(yīng)的ASCII碼組成的數(shù)組
var map = Array.prototype.map var a = map.call("Hello World", function(x) { return x.charCodeAt(0); }) // a的值為[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
-
如何遍歷querySelectorAll得到動(dòng)態(tài)對(duì)象集合
var elems = document.querySelectorAll('select option:checked'); var values = Array.prototype.map.call(elems, function(obj) { return obj.value; }); -
反轉(zhuǎn)字符串
var str = '12345'; Array.prototype.map.call(str, function(x) { return x; }).reverse().join(''); // Output: '54321' -
parseInt等有多個(gè)參數(shù)的函數(shù)要注意
var a = ['1','2','3']; var b = a.map(function(x){ return parseInt(x); }); //[1,2,3] // 下面的語句返回什么呢: ["1", "2", "3"].map(parseInt); // 你可能覺的會(huì)是[1, 2, 3] // 但實(shí)際的結(jié)果是 [1, NaN, NaN] //parseInt有兩個(gè)參數(shù),第二個(gè)數(shù)是進(jìn)制數(shù) //所以以上函數(shù)主要執(zhí)行的是 var a = ['1','2','3']; var b = a.map(function(ele,index,array){ return parseInt(ele,index); //第三個(gè)參數(shù)parseInt會(huì)忽視, 但第二個(gè)參數(shù)不會(huì) // parseInt把傳過來的索引值當(dāng)成進(jìn)制數(shù)來使用 //而第二個(gè)參數(shù)假如經(jīng)過 Number 函數(shù)轉(zhuǎn)換后為 0 或 NaN,則將會(huì)忽略 //parseInt(1,0); 1 //parseInt(2,1); NaN //parseInt(3,2); NaN }) //解決如下 function returnInt(element){ return parseInt(element,10); } ["1", "2", "3"].map(returnInt); // 返回[1,2,3]
-
兼容問題 IE8及以下不支持
// 實(shí)現(xiàn) ECMA-262, Edition 5, 15.4.4.19 // 參考: http://es5.github.com/#x15.4.4.19 // 兼容代碼 if (!Array.prototype.map) { Array.prototype.map = function(callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. 將O賦值為調(diào)用map方法的數(shù)組. var O = Object(this); // 2.將len賦值為數(shù)組O的長度. var len = O.length >>> 0; // 3.如果callback不是函數(shù),則拋出TypeError異常. if (Object.prototype.toString.call(callback) != "[object Function]") { throw new TypeError(callback + " is not a function"); } // 4. 如果參數(shù)thisArg有值,則將T賦值為thisArg;否則T為undefined. if (thisArg) { T = thisArg; } // 5. 創(chuàng)建新數(shù)組A,長度為原數(shù)組O長度len A = new Array(len); // 6. 將k賦值為0 k = 0; // 7. 當(dāng) k < len 時(shí),執(zhí)行循環(huán). while(k < len) { var kValue, mappedValue; //遍歷O,k為原數(shù)組索引 if (k in O) { //kValue為索引k對(duì)應(yīng)的值. kValue = O[ k ]; // 執(zhí)行callback,this指向T,參數(shù)有三個(gè).分別是kValue:值,k:索引,O:原數(shù)組. mappedValue = callback.call(T, kValue, k, O); // 返回值添加到新數(shù)組A中. A[ k ] = mappedValue; } // k自增1 k++; } // 8. 返回新數(shù)組A return A; }; }
forEach
array.forEach(function(value,index,array){},thisArg);
遍歷數(shù)組,跑起來就停不下來,調(diào)用就會(huì)遍歷整個(gè)數(shù)組,無法中斷循環(huán)
回調(diào)函數(shù)的第一個(gè)參數(shù)表示數(shù)組中的每一個(gè)元素,第二個(gè)表示索引號(hào),第三個(gè)表示正在操作的數(shù)組,可選
-
返回值undefined
//實(shí)例 function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } // 注意索引2被跳過了,因?yàn)樵跀?shù)組的這個(gè)位置沒有項(xiàng) [2, 5, ,9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[3] = 9 [2, 5,"" ,9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = // a[3] = 9 -
使用thisArg
因?yàn)閠hisArg參數(shù)(this)傳給了forEach(),每次調(diào)用時(shí),它都被傳給callback函數(shù),作為它的this值。但是在ES6的箭頭函數(shù)表達(dá)式傳入函數(shù)參數(shù),thisArg參數(shù)會(huì)被忽略,因?yàn)榧^函數(shù)在詞法上綁定了this值。
function Counter() { this.sum = 0; this.count = 0; } Counter.prototype.add = function(array) { array.forEach(function(entry) { this.sum += entry; ++this.count; }, this); //console.log(this); }; var obj = new Counter(); obj.add([1, 3, 5, 7]); obj.count; // 4 === (1+1+1+1) obj.sum; // 16 === (1+3+5+7)
-
兼容問題 IE8及以下不支持
// Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.io/#x15.4.4.18 if (!Array.prototype.forEach){ Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this == null) { throw new TypeError(' this is null or not defined'); } // 1. Let O be the result of calling toObject() passing the // |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get() internal // method of O with the argument "length". // 3. Let len be toUint32(lenValue). var len = O.length >>> 0; // 4. If isCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let // T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0 k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty // internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Call the Call internal method of callback with T as // the this value and argument list containing kValue, k, and O. callback.call(T, kValue, k, O); } // d. Increase k by 1. k++; } // 8. return undefined }; }
every
array.every(function(value,index){});
-
根據(jù)當(dāng)前回調(diào)函數(shù)的返回值決定是否進(jìn)行下一次循環(huán)
- 如果沒有return true,則只是執(zhí)行一次
- 回調(diào)函數(shù)的返回值為true,繼續(xù)循環(huán)
- 返回值是false,停止循環(huán)
第一個(gè)參數(shù)是數(shù)組中的每一個(gè)元素 第二個(gè)參數(shù)表示索引號(hào)
-
兼容問題 IE8及以下不支持
//兼容問題 if (!Array.prototype.every){ Array.prototype.every = function(fun /*, thisArg */){ 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++){ if (i in t && !fun.call(thisArg, t[i], i, t)) return false; } return true; }; }
some(返回布爾)
array.some(callback[,thisArg])
callback 被調(diào)用時(shí)傳入三個(gè)參數(shù):元素的值,元素的索引,被遍歷的數(shù)組
thisArg參數(shù),將會(huì)把它傳給被調(diào)用的callback,作為this 值。否則,在非嚴(yán)格模式下將會(huì)是全局對(duì)象,嚴(yán)格模式下是undefined
-
數(shù)組中如果有一個(gè)滿足條件,返回true,否則返回false
//callback function isBigEnough(element, index, array){ return (element >= 10); } var passed = [2, 5, 8, 1, 4].some(isBigEnough); // passed is false passed = [12, 5, 8, 1, 4].some(isBigEnough); // passed is true -
some有兼容問題,IE8及以下不支持
//兼容代碼 if (!Array.prototype.some){ Array.prototype.some = function(fun /*, thisArg */){ 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++){ if (i in t && fun.call(thisArg, t[i], i, t)) return true; } return false; }; }
filter
var new_array = arr.filter(callback[, thisArg])
判斷數(shù)組中的每一項(xiàng)是否都滿足條件,所有滿足條件的則返回新數(shù)組
callback 用來測(cè)試數(shù)組的每個(gè)元素的函數(shù)。調(diào)用時(shí)使用參數(shù) (element, index, array)
返回true表示保留該元素(通過測(cè)試),false則不保留thisArg 可選,執(zhí)行callback時(shí)的用于this的值
-
這些概念去看some
function isBigEnough(element) { return element >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44] //另一種寫法 var arr = [12, 5, 8, 130, 44]; var filt = arr.filter(function(element){ return element >= 10; })//filt is [12, 130, 44]
-
filter有兼容問題,IE8及以下不支持
//兼容代碼 //假定 fn.call 等價(jià)于 Function.prototype.call 的初始值,且 Array.prototype.push 擁有它的初始值。 if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) res.push(val); } } return res; }; }
截取數(shù)組
slice(索引)
array.slice(start,end)
-
start
- 正數(shù),數(shù)組片段開始截取的下標(biāo)
- 負(fù)數(shù),從數(shù)組尾部開始算起,-1是最后一個(gè),-2是倒數(shù)第二個(gè)
- 截取一個(gè)生成新數(shù)組,不影響原來數(shù)組,參數(shù)開始從0開始,從-1結(jié)束
-
end
- 結(jié)束的后一個(gè)元素的數(shù)組下標(biāo)
- 沒有指定參數(shù),則默認(rèn)是到數(shù)組結(jié)束
- 如果是負(fù)數(shù),就是從末尾開始算起
-
截取一個(gè)生成新數(shù)組,不影響原來數(shù)組,包含從start到end(不包括該元素)指定的array元素
var a = [1,2,3,4,5]; a.slice(0,3); // 返回 [1,2,3] a.slice(3); // 返回 [4,5] a.slice(1,-1); // 返回 [2,3,4] a.slice(-3,-2); // 返回 [3]; //IE 4存在的Bug: 返回[1,2,3]
splice(長度,可替換)
array.splice(start, deleteCount, value, ...)
-
參數(shù)有start,deleteCount,options(替換)
- start開始插入和(或)刪除的數(shù)組元素的下標(biāo)
- deleteCount 從start開始(包括start)要?jiǎng)h除的元素個(gè)數(shù)。參數(shù)可選,如果沒有指定,就默認(rèn)到結(jié)尾的所有元素
- value,... 要插入的數(shù)組值,從start所指的下標(biāo)處開始插入
-
返回值是截取到的數(shù)組
//定義一個(gè)數(shù)組 var arr = [10,20,30,40,50,60,70,80,90]; //三個(gè)參數(shù)的情況 從索引為三的地方數(shù)三個(gè),替換這三個(gè)數(shù) var result = arr.splice(3,3,100,200,300); //arr = [10,20,30,100,200,300,70,80,90]; //result = [40,50,60]; //兩個(gè)參數(shù)的情況 從索引為三的地方截取三個(gè) var result1 = arr.splice(3,3); //arr = [10,20,30,70,80,90]; //result = [100,200,300]; //一個(gè)參數(shù)的情況,是從索引為三的地方一直到最后截取 var result2 = arr.splice(3); //arr = [70,80,90] //result2 = [10,20,30]
連接數(shù)組
join(字符串)
var string = array.join()
如果沒有參數(shù),默認(rèn)用逗號(hào)作為分割符
如果有參數(shù),則參數(shù)是用于分隔數(shù)組元素的字符或字符串
返回字符串,通過把a(bǔ)rray每個(gè)元素轉(zhuǎn)換成字符串,用參數(shù)連接起來
-
可以用String對(duì)象的split()方法進(jìn)行相反的操作,把字符串根據(jù)參數(shù)分隔成數(shù)組
var a = new Array(1, 2, 3, "testing"); //a = [1,2,3,testing] var s = a.join("+"); // s 是字符串"1+2+3+testing"
concat
var new_array = array1.concat('array2','array3')
參數(shù)至少是一個(gè)
返回一個(gè)新數(shù)組
-
如果操作的參數(shù)是一個(gè)數(shù)組,那么添加的是數(shù)組中的元素,而不是數(shù)組
var a = [1,2,3]; a.concat(4, 5) //返回 [1,2,3,4,5] a.concat([4,5]); //返回 [1,2,3,4,5] a.concat([4,5],[6,7]) //返回 [1,2,3,4,5,6,7] a.concat(4, [5,[6,7]]) //返回 [1,2,3,4,5,[6,7]]
添加元素
push
array.push(value,...)
要添加到array的末尾,可以是一個(gè)也可以是多個(gè)
返回值是添加后的數(shù)組的長度
pop()方法和push()方法可以提供先進(jìn)后出的棧的功能
-
在對(duì)象中添加元素
var obj = { length: 0, addElem: function addElem(elem){ [].push.call(this, elem); } }; obj.addElem({}); obj.addElem({}); console.log(obj.length); // → 2
unshift
array.unshift(value, ...)
- 參數(shù)是要添加到頭部的一個(gè)或多個(gè)值
- 返回?cái)?shù)組的新長度
移除元素
pop
array.pop()
- 刪除的是數(shù)組中的最后一個(gè)元素,數(shù)組長度-1
- 返回值是刪除的元素
- 如果數(shù)組為空,則數(shù)組長度不變,返回undefined
- pop()方法和push()方法可以提供先進(jìn)后出的棧的功能
shift
array.shift()
移除的是數(shù)組中的第一個(gè)元素,其余的向前移
返回的是移除元素的值
-
如果是空數(shù)組,則不進(jìn)行任何操作,返回undefined
?
數(shù)組排序
sort
arr.sort(compareFunction)
compareFunction 可選。是用來指定按什么順序進(jìn)行排序的函數(shù),可選
返回排序后的數(shù)組
如果不傳參數(shù),將按照字母(字符編碼)順序最數(shù)組進(jìn)行排序,所以要把數(shù)組中的元素轉(zhuǎn)化為字符串以便進(jìn)行比較
-
如過按照別的順序進(jìn)行排序,就要提供比較函數(shù)(參數(shù)a,b)
- a < b 排序后a在b之前,就返回一個(gè)小于0的值
- a = b 返回0
- a > b 排序后a在b之后,返回一個(gè)大于0的值
// 按照數(shù)字順序排序的排序函數(shù) //a-b 表示升序排列 function sortAscending(a, b) { return a - b; } //b-a 表示降序排列 function sortDescending(a,b) { return b - a; } var a = new Array(33, 4, 1111, 222); // 按照字母順序的排序 a.sort(); // 結(jié)果為: 1111, 222, 33, 4 // 按照數(shù)字順序的排序 a.sort(sortAscending); //結(jié)果為: 4, 33, 222, 1111 a.sort(sortDescending); //結(jié)果為:1111,222,33,4
reverse
array.reverse( )
-
顛倒數(shù)組中元素的順序,不創(chuàng)建新數(shù)組
var a = new Array(1, 2, 3); // a = [1,2,3] a[0] == 1, a[2] == 3; a.reverse( ); //Now a = [3,2,1] a[0] == 3, a[2] == 1;
查找數(shù)組
indexOf(返回索引)
arr.indexOf(searchElement)
arr.indexOf(searchElement[, fromIndex = 0])
searchElement 要查找的元素
-
fromIndex 開始查找的位置
- fromIndex >= length,意味著不會(huì)在數(shù)組里查找,返回-1
- 負(fù)值,-1從最后一個(gè)開始查找,-2從倒數(shù)第二個(gè)開始找
-
返回值如果找到了元素就返回元素在數(shù)組中的索引位置,若沒有找到則返回-1
var array = [2, 5, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0 -
找出指定元素出現(xiàn)的所有位置
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; //判斷元素在不在數(shù)組里面 var idx = array.indexOf(element); //如果元素在數(shù)組里面,就循環(huán) while (idx != -1) { //把索引推入新數(shù)組中 indices.push(idx); //從找到元素的下一個(gè)索引開始繼續(xù)查找 idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4] -
判斷一個(gè)元素是否在數(shù)組里,不在則更新數(shù)組
//定義一個(gè)函數(shù) function update(vegs, veg) { //如果數(shù)組中不存在 if (vegs.indexOf(veg) === -1) { //在數(shù)組中添加元素 vegs.push(veg); console.log('New vegs is :' + vegs); //如果在數(shù)組中存在 } else if (vegs.indexOf(veg) > -1) { //這個(gè)元素已經(jīng)存在在數(shù)組中 console.log(veg + ' already exists in the vegs.'); } } var vegs = ['potato', 'tomato', 'chillies', 'green-pepper']; update(vegs, 'spinach'); // New vegs is : potato,tomato,chillies,green-papper,spinach update(vegs, 'spinach'); // spinach already exists in the vegs. -
兼容問題 IE8及以下不兼容
//兼容代碼 // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; }
?copyright burning.