主题
常用工具函数
jQuery 不仅提供 DOM 操作和 AJAX 功能,还包含丰富的工具函数,便于处理数组、对象和字符串等常见任务。
1. $.each()
用于遍历数组或对象。
js
$.each([1, 2, 3], function (index, value) {
console.log(index + ": " + value);
});
2. $.extend()
合并对象,常用于配置合并。
js
var defaults = { a: 1, b: 2 };
var options = { b: 3, c: 4 };
var result = $.extend({}, defaults, options);
console.log(result); // {a:1, b:3, c:4}
3. $.trim()
去除字符串两端空白。
js
var str = " hello world ";
console.log($.trim(str)); // "hello world"
4. $.isArray()
判断是否为数组。
js
console.log($.isArray([1, 2, 3])); // true
console.log($.isArray("abc")); // false
5. $.parseJSON()
解析 JSON 字符串(现代浏览器已推荐使用 JSON.parse)。
js
var jsonStr = '{"name":"jQuery"}';
var obj = $.parseJSON(jsonStr);
console.log(obj.name); // jQuery
示例代码
loading