簡體   English   中英

jQuery map與每個

[英]jQuery map vs. each

在jQuery中, mapeach函數似乎都做同樣的事情。 兩者之間是否存在實際差異? 你什么時候選擇使用一個而不是另一個?

each方法都是一個不可變的迭代器,因為map方法可以用作迭代器,但實際上是為了操作提供的數組並返回一個新數組。

另一個需要注意的重要事項是, each函數返回原始數組,而map函數返回一個新數組。 如果過度使用map函數的返回值,則可能會浪費大量內存。

例如:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});
// newItems is [2,3,4,5]

您還可以使用map函數從數組中刪除項目。 例如:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5) 
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]

您還會注意到, this不會映射到map功能中。 您將必須在回調中提供第一個參數(例如,我們在上面使用過i )。 具有諷刺意味的是,每個方法中使用的回調參數與map函數中的回調參數相反,因此要小心。

map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});

1:回調函數的參數相反。

.each()$.each().map()的回調函數首先獲取索引,然后是元素

function (index, element) 

$.map()的回調具有相同的參數,但是相反

function (element, index)

2: .each() $.each().map()做一些特別的東西與this

each()調用以這樣的方式,該函數this指向當前元素。 在大多數情況下,您甚至不需要回調函數中的兩個參數。

function shout() { alert(this + '!') }

result = $.each(['lions', 'tigers', 'bears'], shout)

// result == ['lions', 'tigers', 'bears']

對於$.map()this變量引用全局窗口對象。

3: map()對回調的返回值做了一些特殊的事情

map()在每個元素上調用函數,並將結果存儲在它返回的新數組中。 您通常只需要使用回調函數中的第一個參數。

function shout(el) { return el + '!' }

result = $.map(['lions', 'tigers', 'bears'], shout)

// result == ['lions!', 'tigers!', 'bears!']

each一個數組函數迭代,調用提供的函數每一次元件,並且設置this到有源元件。 這個:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

將提醒5..然后4..然后3..然后2..然后1..

另一方面,Map采用數組,並返回一個新數組,其中每個元素都由函數更改。 這個:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

會導致s為[25, 16, 9, 4, 1]

我明白這個

function fun1() {
    return this + 1;
}
function fun2(el) {
    return el + 1;
}

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

var newitem1 = $.each(item, fun1);
var newitem2 = $.map(item, fun2);

console.log(newitem1); // [5, 4, 3, 2, 1] 
console.log(newitem2); // [6, 5, 4, 3, 2] 

所以,“ each ”函數返回原始數組,而“ map ”函數返回一個新數組

var intArray = [1, 2, 3, 4, 5];
//lets use each function
$.each(intArray, function(index, element) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
});

//lets use map function
$.map(intArray, function(element, index) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2,4,5. skip the number 3.
});

當你在數組上工作時,Jquery.map更有意義,因為它對數組表現很好。

在迭代選擇器項時最好使用Jquery.each。 這證明了map函數不使用選擇器。

$(selector).each(...)

$.map(arr....)

如您所見,map不適用於選擇器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM