jquery中map函数与each函数的区别实例介绍


​jquery中的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]


​使用each时,改变的还是原来的items数组,而使用map时,不改变items,只是新建一个新的数组。

​例如:

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]

当需要对数组进行删除时也是如此,所以删除时错误使用each或map后果还是蛮严重的。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3