DIV CSS 佈局教程網

JS常用陣列操作方法簡明總結
編輯:JavaScript基礎知識     

以下透過一系列範例,把JavaScript陣列最常用的操作方法做個快速整理。

 //陣列分割(join)
var colors = ["red","green","blue"];
alert(colors.join("|")); //red|green|blue

var colors = ["red","green","blue",null];
alert(colors.join("|")); //red|green|blue|
//注意:當陣列中有 null 或 undefined 時,該位置以空字串表示

//陣列添加(push / unshift)
var colors = ["red","green","blue"];
colors.push("white","test"); //回傳新長度
alert(colors.join("|")); //red|green|blue|white|test

var colors = ["red","green","blue","test"];
colors.unshift("first"); //在開頭添加
alert(colors.join("|")); //first|red|green|blue|test

//陣列刪除(pop / shift)
var colors = ["red","green","blue","test"];
var item = colors.pop(); //刪除並回傳最後一項 test
alert(colors.join("|")); //red|green|blue

var colors = ["red","green","blue","test"];
var item = colors.shift(); //刪除第一項
alert(colors.join("|")); //green|blue|test

//反轉與排序
var colors = ["red","green","blue","test"];
colors.reverse();
alert(colors); //test,blue,green,red

var values = [0,1,5,10,7];
values.sort(compare);
alert(values);
function compare(value1,value2){
 if(value1<value2){ return 1; }
 else if(value1>value2){ return -1; }
 else return 0;
}

//concat 合併陣列
var colors = ["color","red"];
var colors2 = colors.concat(["ccc","bbbb"],'3333',['vvccxx',['oolll','lll']]);
alert(colors2);//color,red,ccc,bbbb,3333,vvccxx,oolll,lll

//slice 複製元素(不影響原陣列)
var colors = ["color","red",'eeee','221111'];
var colors2 = colors.slice(1); //從索引1開始
alert(colors2);//red,eeee,221111

var colors = ["color","red",'eeee','221111'];
var colors2 = colors.slice(1,3); //索引1到3-1
alert(colors2);//red,eeee

//splice 刪除與插入
var a = [1,2,3,5,8];
var r = a.splice(0,2); //刪除前2項
alert(a);//3,5,8

var a = [1,2,3,5,8];
var r = a.splice(1,1,100,200); //從索引1刪除1項並插入100、200
alert(a);//1,100,200,3,5,8

從範例可歸納出幾個要點:join 用於把陣列串接成字串,遇到 null/undefined 會轉為空字串;push 與 unshift 分別在尾端與前端新增元素並回傳新長度;pop 與 shift 分別移除尾端與前端元素並回傳該值;reverse 反轉、sort 排序(可傳入自訂比較函式);concat 合併、slice 複製片段、splice 則是萬能的「刪除+插入」工具。掌握這幾個方法,日常陣列操作綽綽有餘。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved