简体   繁体   中英

Using jQuery.each() to manipulate the elements of an Array/Object in place

Playing around with JavaScript and jQuery over here. Making a function that produces timestamps.

I've got the following code:

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];
};

This code fails, because, $.each() binds the callback to the element it's working on rather than the iterable, as such:

// 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;
    }
}

Now, to get the binding I want, I can change the offending line in my code to:

$.each(components, $.proxy(components.zero_pad, components));

but here I invoke even more framework code and this is starting to look quite messy.

I feel like I'm missing something! Is there a simpler way to modify the contents of an array in place?

It would be far easier to replace all your zero_pad stuff with something simpler, like this:

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]);
}

please ignore the following if I'm off base- but I was curious what you were trying to get at, is this "sorta" what you are trying to achieve?

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());
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM