DIV CSS 佈局教程網

JavaScript 學習日記:Array 陣列的 16 個核心方法
編輯:關於JavaScript     

toString 與 valueOf

 var colors = ["red", "blue", "green"]; //creates an array with three strings
alert(colors.toString()); //red,blue,green
alert(colors.valueOf());  //red,blue,green
alert(colors);            //red,blue,green

map:一對一映射

 var numbers = [1,2,3,4,5,4,3,2,1];
var mapResult = numbers.map(function(item, index, array){
  console.log(array === numbers);//true
  return item * 2;
});
console.log(mapResult); //[2,4,6,8,10,8,6,4,2]

回調收到三個參數:元素、索引、原陣列。回傳值組成同長度的新陣列,原陣列不受影響。

reduce:聚合為單一值

 var values = [1,2,3,4,5];
//接收一個函數,然後從左到右遍歷item,直到reduce到一個值。
var sum = values.reduce(function(prev, cur, index, array){
  console.log(array === values);
  console.log(index);//1,2,3,4
  return prev + cur;
});
alert(sum);//15

concat:合併且不改原陣列

 //concat() 方法用於連接兩個或多個數組,不會改變現有數組,僅返回副本。
var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors);  //red,green,blue
alert(colors2); //red,green,blue,yellow,black,brown

length:長度不只是唯讀

 var colors = new Array(3);          //create an array with three items
var names = new Array("Greg");      //create an array with one item
alert(colors.length);//3
alert(names.length);//1
 var colors = ["red", "blue", "green"];
var names = [];        //creates an empty array
var values = [1,2,];   //AVOID! 2 or 3 items
var options = [,,,,,]; //AVOID! 5 or 6 items
alert(colors.length);  //3
alert(names.length);   //0
alert(values.length);  //2 (FF, Safari, Opera) or 3 (IE)
alert(options.length); //5 (FF, Safari, Opera) or 6 (IE)

結尾多一個逗號,各瀏覽器解析結果不同,實務上要避免這種寫法。

 var colors = ["red", "blue", "green"];
colors.length = 2;
alert(colors[2]); //undefined
 var colors = ["red", "blue", "green"];
colors.length = 4;
alert(colors[3]); //undefined

length 可寫入:設小會截斷,設大會產生稀疏的空位。

 var colors = ["red", "blue", "green"];
colors[colors.length] = "black"; //add a color
colors[colors.length] = "brown"; //add another color
alert(colors.length); //5
alert(colors[3]); //black
alert(colors[4]); //brown
 var colors = ["red", "blue", "green"];
colors[99] = "black"; //add a color (position 99)
alert(colors.length); //100

用 colors[colors.length] 追加元素,等價於 push,而且不會有型別轉換的困擾。

every 與 some

 //every():每一項都回true才回true
//some():任一項回true就回true
var numbers = [1,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item, index, array){
  return (item > 2);
});
alert(everyResult); //false
var someResult = numbers.some(function(item, index, array){
  return (item > 2);
});
alert(someResult); //true

filter:篩選

 var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item, index, array){
  return (item > 2);
});
alert(filterResult); //[3,4,5,4,3]

indexOf 與 lastIndexOf

 //indexOf():首次出現的位置
//lastIndexOf():從後往前找,回傳最後出現的位置
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4));     //3
alert(numbers.lastIndexOf(4)); //5
alert(numbers.indexOf(4, 4));  //5
alert(numbers.lastIndexOf(4, 4)); //3

var person = { name: "Nicholas" };
var people = [{ name: "Nicholas" }];
var morePeople = [person];
alert(people.indexOf(person));     //-1
alert(morePeople.indexOf(person)); //0

這段說明了關鍵一點:indexOf 比的是「參照」,不是內容。兩個長得一模一樣的物件,仍然找不到。

toString 與 toLocaleString

 var person1 = { toLocaleString : function () { return "Nikolaos"; },
                toString : function() { return "Nicholas"; } };
var person2 = { toLocaleString : function () { return "Grigorios"; },
                toString : function() { return "Greg"; } };
var people = [person1, person2];
alert(people);                  //Nicholas,Greg
alert(people.toString());       //Nicholas,Greg
alert(people.toLocaleString()); //Nikolaos,Grigorios

push 與 pop

 var colors = new Array();
var count = colors.push("red", "green"); //push two items
alert(count); //2
count = colors.push("black");            //push another item on
alert(count); //3
var item = colors.pop();                 //get the last item
alert(item);  //"black"
alert(colors.length); //2

unshift 與 shift

 //unshift():從頭加入,回傳新長度
//shift():移除第一個元素並回傳它
var colors = new Array();
var count = colors.unshift("red", "green");
alert(count); //2
count = colors.unshift("black");
alert(count); //3
var item = colors.pop();
alert(item);  //"green"
alert(colors.length); //2

reverse

 var values = [1, 2, 3, 4, 5];
values.reverse();
alert(values); //5,4,3,2,1

sort

 function compare(value1, value2) {
  if (value1 < value2) { return -1; }
  else if (value1 > value2) { return 1; }
  else { return 0; }
}
var values = [0, 1, 16, 10, 15];
values.sort(compare);
alert(values); //0,1,10,15,16
//sort 改變原數組

不傳比較函式時,sort 會把元素轉成字串排序,所以 [1,16,10] 會排成 1,10,16 以外的意外順序——這就是為什麼數字排序一定要自己寫 compare。

slice:擷取不重排

 /* slice() 從已有數組中返回選定的元素,不修改原數組。
   start 必需,可為負數(從尾端算起,-1 是最後一個)。
   end 可選,為結束處的下標,結果不含該元素。 */
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(colors2); //green,blue,yellow,purple
alert(colors3); //green,blue,yellow

splice:插入與刪除

 /* splice() 向/從數組添加/刪除項目,返回被刪除的項目,會改變原數組。
   index 必需,起始位置,可為負數。
   howmany 必需,要刪除的數量,設 0 則不刪除。
   item1...itemX 可選,要插入的新項目。 */
var colors = ["red", "green", "blue"];
var removed = colors.splice(0,1); //remove the first item
alert(colors);  //green,blue
alert(removed); //red

removed = colors.splice(1, 0, "yellow", "orange"); //insert two items
alert(colors);  //green,yellow,orange,blue
alert(removed); //empty array

removed = colors.splice(1, 1, "red", "purple"); //insert two, remove one
alert(colors);  //green,red,purple,orange,blue
alert(removed); //yellow

isArray

 alert(Array.isArray([]));  //true
alert(Array.isArray({}));  //false

typeof [] 會回傳 "object",所以判斷陣列不能靠 typeof,Array.isArray() 才是正解。

以上就是本次的陣列方法整理,後續會持續補充。

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