ここで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));
しかし、ここで私はさらに多くのフレームワークコードを呼び出し、これはかなり厄介に見え始めています。
何かが足りない気がします!配列の内容を適切に変更する簡単な方法はありますか?