js中陣列實用方法

2022-09-09 14:27:17 字數 3136 閱讀 4288

shift用法和un****用法

var  colors = [ 'red', 'blue'];

var item =colors.shift();

alert(item);

//'red'

alert(colors.length); //

1

var colors = ['red','blue'];

var count = colors.unshift('green','back');

alert(count); //4

alert(colors.join(',')); //

'back','green','red','blue'

sort用法

sort方法預設按照元素內內首個字元的ascii碼值公升序排序的

var arr = [5,1,4,11,2].sort();

console.log(arr);

//[1, 11, 2, 4, 5]

如要實現完整的陣列元素值按公升序排列,則應傳遞乙個處理函式

function

compare(val1, val2)

else

if(val1 >val2)

else

};var values = [5, 1, 11, 2];

values.sort(compare);

console.log(values);

//[1, 2, 5, 11]

concat用法

var a =[1, 2];

a.concat(3, [4, 5]);

console.log(a);

//[1,2,3,4,5];

slice用法

slice函式操作後不影響原素組

var colors = ['red', 'green', 'blue'];

var colors2 = colors.slice(1); //

['green', 'blue'];

var colors3 = colors.slice(1, 2); //

['green'];

console.log(colors); //

['red', 'green', 'blue'];

tips:如果slice方法中的引數有乙個負數,則用陣列長度加上該值確定相應的位置值

如陣列長度為5時, slice.(-2, -1) 等價於 slice(3, 4);

巧妙使用改特性獲取陣列中特定後幾位元素

var a = [1,2,3,4,5,6,7];

var b = a.slice(4); //

[4,5,6,7]

splice用法

刪除功能: 指定兩個引數, 要刪除的第一項的位置和要刪除的項數

var colors = ['red', 'green', 'blue'];

var removed = colors.splice(0,1);

alert(colors);

//'green', 'blue'

alert(removed); //

'red'

插入功能:指定3個引數:起始位置、0(要刪除的項數),要插入的項

removed = colors.splice(1, 0, 'yellow', 'orange'); //

從位置1開始插入兩項

alert(colors); //

green, yellow, orange, blue

alert(removed); //

返回的是乙個空陣列

替換功能:指定3個引數:起始位置、要刪除的項數,要插入的項

removed = colors.splice(1, 1, "red", "purple"); //

插入兩項,刪除一項

alert(colors); //

green,red,purple,orange,blue

alert(removed); //

yellow 返回的陣列中只包含一項

迭代方法

every:對陣列中的每一項執行給定函式,如果該函式對每一項都返回true,則返回true,

some:對陣列中的每一項執行給定函式,如果該函式對任意一項返回true,則返回true,

foreach:對陣列中的每一項執行某些操作

filter: 對陣列中的每一項執行給定函式,返回該函式會返回true的項組成的陣列

map:對陣列中的每一項運算給定函式,返回每次函式呼叫的結果組成的陣列

var number = [1,2,3,4,5,4,3,2,1];

var everyresult = numbers.every(function

(item,index,array))

alert(everyresult);

//false;

var someresult = numbers.every(function

(item,index,array))

alert(someresult);

//true;

numbers.foreach(

function

(item,index,array))

var filterresult = numbers.filter(function

(item,index,array))

alert(filterresult);

//[3,4,5,4,3];

var mapresult = numbers.map(function

(item,index,array))

alert(mapresult);

//[2,4,6,8,10,8,6,4,2];

js實用方法

判斷型別 千位符const milliformat num num num.tostring replace d g,m m.replace d g,深度轉殖 function deepclone obj var o isarray obj for i in obj return o 解析get請求...

js中公用方法彙總 實用

時間轉換方法 時間轉換方法 1 thu mar 07 2019 12 00 00 gmt 0800 中國標準時間 轉 時間戳 1508750413 時間戳 1000就是毫秒數 2日期轉 時間戳 1508750413 時間戳 1000就是毫秒數 timevalue 中國標準時間 standardcha...

JS 日期實用方法

var dateutil function 日期物件轉換為指定格式的字串 param f 日期格式,格式定義如下 yyyy mm dd hh mm ss param date date日期物件,如果預設,則為當前時間 yyyy yyyy yy yy 表示年份 mm m 月份 w w 星期 dd dd...