簡體   English   中英

使用jQuery.each()在適當位置操縱數組/對象的元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM