Skip to content

Instantly share code, notes, and snippets.

@ashikawa
Created November 9, 2012 15:06
Show Gist options
  • Save ashikawa/4046204 to your computer and use it in GitHub Desktop.
Save ashikawa/4046204 to your computer and use it in GitHub Desktop.
コードリーディング $.each

$.each のコード

function (object, callback, args) {
    var name, i = 0,
        length = object.length,
        isObj = length === undefined || jQuery.isFunction(object);
    // ....
}

http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.each

    length = object.length,
(function () {}).length     => 0
({'key':'value'}).length    => undefined
({'length':'value'}).length =>"value"
[1, 2, 3].length            => 3
(n = 3).length              => undefined
"string".length             => 6

演算子の優先順位

    isObj  = ( (length === undefined) || jQuery.isFunction(object) );
$.isFunction(function () {});   // => true
$.isFunction({'key': 'value'}); // => false
$.isFunction([1, 2, 3]);        // => false
$.isFunction(3);                // => false
$.isFunction("string");         // => false
function isObj(object) {
	var length = object.length;
	return length === undefined || jQuery.isFunction(object);
}


isObj((function () {}));        // => true
isObj(({'key': 'value'}));      // => true
isObj(({'length': 'value'}));   // => false バグ ?
isObj([1, 2, 3]);               // => false
isObj(3);                       // => true
isObj("string");                // => false
function hoge(){};
hoge.moge  = 1;
hoge.moge2 = 2;

$.each(hoge, function (key, value) {
	console.log(key, value)
});

教訓

  • 自分で length を設定する時は注意。 ( というか余計な事はしない方が良い )
  • 数字も通るけど、単に無視される
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment