[英]Using jQuery.each() to manipulate the elements of an Array/Object in place
在这里使用JavaScript和jQuery。 制作产生时间戳的函数。
我有以下代码:
var timestamp = function () {
var now = new Date();
var components = [now.getHours(), now.getMinutes(), now.getSeconds()];
components.zero_pad = function(index, component) {
// When this function is called with `$.each()` below,
// `this` is bound to `component`, not `components`.
// So, this code fails, because you can't index a Number.
this[index] = (this[index].toString().length == 1) ?
'0' + component : component;
}
// Offending line
$.each(components, components.zero_pad);
return components[0] + ':' + components[1] + ':' + components[2];
};
这段代码失败了,因为$.each()
将回调绑定到它正在处理的元素而不是可迭代的元素,如下所示:
// from jQuery.each()
for ( ; i < length; i++ ) {
// I would have guessed it would be
// value = callback.call( obj, i, obj[ i ] );
// but instead it's:
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
现在,要获得所需的绑定,我可以将代码中的违规行更改为:
$.each(components, $.proxy(components.zero_pad, components));
但是在这里,我调用了更多的框架代码,这看起来似乎很混乱。
我觉得我想念什么! 有没有更简单的方法来修改数组中的内容?
用更简单的东西替换所有zero_pad
东西会容易得多,如下所示:
var timestamp = function() {
var now = new Date(), parts = [now.getHours(), now.getMinutes(), now.getSeconds()],
pad = function(n) {return n < 10 ? "0"+n : n;};
return pad(parts[0])+":"+pad(parts[1])+":"+pad(parts[2]);
}
如果我不在基地,请忽略以下内容-但我很好奇您想要达到的目标,这是您要实现的“ sorta”吗?
jQuery(document).ready(function () {
var now = new Date();
var components = [now.getHours(), now.getMinutes(), now.getSeconds()];
var timestamp = {
storage : {},
zero_pad : function() {
storage = $.grep(components,function(obj,i){
return obj = (obj.toString().length == 1) ? '0' + components : components;
});
return storage;
}
};
console.log(timestamp.zero_pad());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.