7.1 陣列(Array)相關

$.isArray() 判斷是否為陣列

說明:判斷是否為陣列。

語法:

let items = [1, 2, 3];
$.isArray(items); // true

let items2 = 123;
$.isArray(items2) // false

範例:

$.inArray() 判斷是否有該值

說明:有的話,回傳該值的索引值;沒有的話,回傳 -1

語法:

let items = [1, 2, 3];
  
alert( $.inArray(1, items) ); // 回傳 1 的索引值:0
alert( $.inArray(3, items) ); // 回傳 3 的索引值:2
alert( $.inArray(4, items) ); // 回傳 4 的索引值,因為找不到,故回傳 -1

範例:

$.merge() 陣列的合併

說明:將第二個陣列合併到第一個陣列。

例:

let items = [1, 2, 3];
let items2 = [2, 3, 4];
  
$.merge(items, items2);
  
console.log(items);  // [1, 2, 3, 2, 3, 4]
console.log(items2); // [2, 3, 4]

實測:

$.each() 跑陣列、物件迴圈

說明:將陣列依序跑迴圈。

語法一:

let items = [1, 2, 3, 4]; // 陣列
//let items = {a: "one", b: "two", c: "three"}; // 物件

$.each(items, function(index, item){
  console.log("索引值:" + index + "; 值:" + item)
});

語法二:直接用在選擇子所選到的元素陣列

$("p").each(function(index, item){
  console.log("索引值:" + index + "; 內容:" + $(item).text());
});

範例:

$.map() 跑完迴圈後會產生新的陣列或物件

說明:與 $.each() 很類似,但 $.map() 跑完迴圈後,會回傳新的陣列或物件。

語法:

let items = ["a", "b", "c", "d"]; // 陣列

let new_data = $.map(items, function(item, index){ // 這裡第二個參數是索引值
  return item + index;
});

console.log(new_data); // ["a0", "b1", "c2", "d3"]
console.log(items);    // ["a", "b", "c", "d"]
let items = {a: "one", b: "two", c: "three"}; // 物件

let new_data = $.map(items, function(item, index){ // 這裡第二個參數是索引值
  return item + index;
});

console.log(new_data); // ["onea", "twob", "threec"]
console.log(items);    // {a: "one", b: "two", c: "three"}

範例:

Last updated