在这里玩 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));
但是在这里我调用了更多的框架代码,这开始看起来很混乱。
我觉得我错过了什么!有没有更简单的方法来修改数组的内容?