gpt4 book ai didi

javascript - 用于快速迭代的 jquery 范围实用程序(原型(prototype)的 $R 等价物)

转载 作者:行者123 更新时间:2023-11-29 17:32:07 25 4
gpt4 key购买 nike

在原型(prototype)中很麻烦:

for (i=0; i<10; i++) { ... }

可以写成

$R(0, 10).each(function(i){ ... });

JQuery 中是否有等效的范围?

最佳答案

参见 http://code.google.com/p/jquery-utils/source/browse/trunk/src/jquery.arrayUtils.js?r=452

jQuery 本身不提供范围扩展,但很容易添加。它只有两个部分。首先,范围函数应该返回一个数组,范围内的每一项都扩展为一个数组值。接下来将一个方法添加到 Array 以迭代每个传入处理程序函数的对象。

这里我们定义了 forEach,它是 ECMA-262 标准的一部分,用于遍历数组。参见 MDC了解更多详情。

if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();

var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}

接下来,我们需要一个函数来将范围扩展到 jQuery 命名空间中的数组。取自上述 URL(原始来源 - http://blog.outofhanwell.com/2006/03/29/javascript-range-function/):

$.extend({
// Returns a range object
// Author: Matthias Miller
// Site: http://blog.outofhanwell.com/2006/03/29/javascript-range-function/
range: function() {
if (!arguments.length) { return []; }
var min, max, step;
if (arguments.length == 1) {
min = 0;
max = arguments[0]-1;
step = 1;
}
else {
// default step to 1 if it's zero or undefined
min = arguments[0];
max = arguments[1]-1;
step = arguments[2] || 1;
}
// convert negative steps to positive and reverse min/max
if (step < 0 && min >= max) {
step *= -1;
var tmp = min;
min = max;
max = tmp;
min += ((max-min) % step);
}
var a = [];
for (var i = min; i <= max; i += step) { a.push(i); }
return a;
}
});

好了,现在我们可以做:

$.range(2, 10).forEach(function(v) {
console.log(v); // 2, 3, 4, .., 9
});

或者将其与自定义步长值而不是 1 一起使用

$.range(2, 20, 4).forEach(function(v) {
console.log(v); // 2, 6, 10, 14, 18
});

关于javascript - 用于快速迭代的 jquery 范围实用程序(原型(prototype)的 $R 等价物),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2855718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com