Laura: Schneller Check, ob array und/oder HTMLCollection/NodeList/Args

Beitrag lesen

Vielleicht unvorbildliche Forums-Nutzung, in kleinen Happen viele Antworten
zum eigenen Thread zu posten, aber wollte hier doch noch kurz schreiben, was ich
bislang habe, weil ja vermutlich Leute mit ähnlichen Fragen hier landen.

Wahrscheinlich reicht so etwas aus:

if (!arg) return; // Sämtliche falsy values sind wahrscheinlich unbenutzbar

if (typeof arg == 'string') {
  // Behandle als Selektor
} else if (typeof arg.length == 'number' && arg[0]) {
  for (var i, l = arg.length; i < l; i++) {
    // Als Liste behandeln
  }
} else {
  // Behandle als Object (Hash)
}

Habe nochmal jQuery etwas durchforstet und bin momentan bei folgendem Code  
(wird noch weiter verbessert werden (z.b. werde ich noch NodeLists gegenchecken etc.):  
~~~javascript
  
typeOf : function(obj) {  
	// ''  
	if (obj == null) { return String(obj); }  
	// HTML nodes  
	if (obj.nodeName) {  
		if (this.isElem(obj)) { return 'element'; }  
		if (this.isTxt(obj)) { return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace'; }  
	}  
	// array-like lists and strings  
	else if (obj.length === +obj.length) {  
		// handle strings before collections -> in-operator throws error on strings!  
		if (typeof obj === 'string') { return 'string'; }  
		if (obj.callee) { return 'arguments'; }  
		if ('item' in obj) { return 'collection'; }  
	}  
	// work with shortcuts instead of bulky '[object Object]', ...  
	return types[ toString.call(obj) ] || 'object';  
},  
isArr : function(obj) {  
// Alias for isArray  
	if (!obj) { return false; }  
	// use native meth if browser supports it  
	if (obj.isArray) { return Array.isArray(obj);  
	} else { return this.typeOf(obj) === 'array'; }  
},  
isArraylike : function(obj) {  
	if (!obj) { return false; }  
	var type = this.typeOf(obj);  
	return type === 'array' || type === 'collection' || type === 'arguments';  
}  

An einigen Stellen werden Framework-interne Methoden und shortcuts verwendet (isElem, isTxt, toString etc.),
aber denke, dass deren Namen ihren Zweck hinreichend vermitteln ;}
types ist ein Objekt-Literal, das so aussieht:

  
var types = {  
   '[object String]' : 'string',  
   '[object Array]' : 'array',  
   usw.  
}  

Lieben Gruß