Home  >  Article  >  Web Front-end  >  Summary of common data processing usage examples in jQuery

Summary of common data processing usage examples in jQuery

伊谢尔伦
伊谢尔伦Original
2017-06-19 11:06:371265browse

这里主要介绍了jQuery常用数据处理用法 , 实例总结了trim、param、isArray、isFunction、each等jQuery常用的数据处理方法。初学jQuery的朋友们可以参考其用法。

1. $.trim():删除字符串前后的空白字符。

var str = ' 薯条 ';
var formatStr = $.trim(str);  //'薯条'

2. $.param():数组或者对象序列化

var obj = {
  name: 'dog',
  count: 10
};
var str = $.param(obj); //"name=dog&count=10"

3. $.isArray():检测是否为数组。
4. $.isFunction():检测是否为函数类型。
5. $.each(obj, [callback]):遍历数组或者集合对象。obj是要遍历的集合对象,callback表示回调函数,该函数将在遍历每个成员时出发。回调函数包含两个参数,第一个参数为对象成员或数组的索引,第二个参数为对应的值。

var a = [x,y,z];
$.each(a, function(index, value) {
  console.log(index); //0,1,2
  console.log(value); //x,y,z
});
var b = {x:1, y:2, z:3};
$.each(b, function(key, value)) {
  console.log(key);  //x,y,z
  console.log(value); //1,2,3
}

说明:如果中途要退出each()循环,可以在回调函数中返回false,其他返回值将被忽略。

$.each()和$(selector).each()功能相同,但$.each()可以遍历任何对象或数组,而$(selector).each()只能遍历当前选择器选择的jQuery对象。

6. $.makeArray():把类数组对象转换为数组对象。所谓类数组对象,就是拥有length属性,索引从0到length-1。但是这些对象不能够调用数组方法。

var arr = $.makeArray($('li')); //类数组对象转换为数组
$('ul').html(arr.reverse()); //可以调用数组的reverse()方法了

7. $.grep():根据过滤函数过滤掉数组中不符合条件的元素。

$.grep(array, callback, [invert]);

说明:参数array表示要过滤的数组,callback表示过滤函数。如果过滤函数返回true,则保留元素,如果过滤函数返回false,则删除元素。参数invert,可选,如果为false或者没有设置,则返回数组中由过滤函数返回true的元素;如果该参数为true,则返回过滤函数中返回false的元素。

var a = [1,2,3,4,5];
a = $.grep(a, function(value, index)) {
  return value > 3; //a现在为[4,5]
});
var b = [1,2,3,4,5];
b = $.grep(b, function(value, index)) {
  return value > 3; //b现在为[1,2,3]
}, true);

8. $.map():映射数组。
$.map(array, callback);

var a = [1,2,3,4];
a = $.map(a, function(elem)) {
  return elem * 2; //a现在为[2,4,6,8]
});

9. $.merge():合并数组。
说明:接受两个数组参数。

var a = [1,2,3];
var b = [4,5];
var c = $.merge(a,b); //c为[1,2,3,4,5];

10. $.unique():删除DOM元素数组中的重复项。

...
<a id="1" class="link link1"></a>
<a id="2" class="link"></a>
<a id="3" class="link"></a>
...
var $link = $(&#39;.link&#39;); //包含#1,#2,#3
var $firstLink = $(&#39;.link1&#39;); //包含#1
var $links = $.merge($link, $firstLink); //包含#1,#2,#3,#1
var $linkList = $.unique($link); //包含#1,#2,#3

说明:只能处理DOM元素数组,不能处理字符串或者JavaScript数组

The above is the detailed content of Summary of common data processing usage examples in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn