0

在这里玩 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));

但是在这里我调用了更多的框架代码,这开始看起来很混乱。

我觉得我错过了什么!有没有更简单的方法来修改数组的内容?

4

2 回答 2

0

用更简单的东西替换所有东西会容易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]);
}
于 2013-03-02T03:35:35.103 回答
0

如果我不在基地,请忽略以下内容-但我很好奇您想要达到什么目的,这是您想要实现的“排序”吗?

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());
 });
于 2013-03-02T04:19:05.227 回答