javascript - Perform a single function on multiple object -
is possible perform single function on multiple objects e.g. grouping them. want like:
{object1, object2, object3}.tofront();
while you've accepted answer, possible in similar manner either natively through javascript 1.6/ecmascript 5th edition:
function logelementid(element, index, array) { var el = array[index], prop = el.textcontent ? 'textcontent' : 'innertext'; el[prop] = el.id; } [document.getelementbyid('one'), document.getelementbyid('two')].foreach(logelementid);
or extending object
prototype:
function dostuff (el) { console.log(el); }; object.prototype.actongroup = function(func){ var els = this.length ? : [this]; (var = 0, len = els.length; i<len; i++){ func(els[i]); } return this; }; document.getelementsbytagname('div').actongroup(dostuff); document.getelementbyid('one').actongroup(dostuff);
or by, similarly, extending array
prototype:
function dostuff (el) { console.log(el); }; array.prototype.actongroup = function(func){ var els = this.length ? : [this]; (var = 0, len = els.length; i<len; i++){ func(els[i]); } return this; }; [document.getelementbyid('one'), document.getelementbyid('two')].actongroup(dostuff);
incidentally, if you'd provide foreach()
alternative users without (relatively) up-to-date javascript implementations, mozilla developer network page foreach()
offers following '[an] algorithm 100% true ecma-262, 5th edition':
// production steps of ecma-262, edition 5, 15.4.4.18 // reference: http://es5.github.com/#x15.4.4.18 if (!array.prototype.foreach) { array.prototype.foreach = function foreach(callback, thisarg) { var t, k; if (this == null) { throw new typeerror("this null or not defined"); } // 1. let o result of calling toobject passing |this| value argument. var o = object(this); // 2. let lenvalue result of calling internal method of o argument "length". // 3. let len touint32(lenvalue). var len = o.length >>> 0; // hack convert o.length uint32 // 4. if iscallable(callback) false, throw typeerror exception. // see: http://es5.github.com/#x9.11 if ({}.tostring.call(callback) !== "[object function]") { throw new typeerror(callback + " not function"); } // 5. if thisarg supplied, let t thisarg; else let t undefined. if (thisarg) { t = thisarg; } // 6. let k 0 k = 0; // 7. repeat, while k < len while (k < len) { var kvalue; // a. let pk tostring(k). // implicit lhs operands of in operator // b. let kpresent result of calling hasproperty internal method of o argument pk. // step can combined c // c. if kpresent true, if (object.prototype.hasownproperty.call(o, k)) { // i. let kvalue result of calling internal method of o argument pk. kvalue = o[k]; // ii. call call internal method of callback t value , // argument list containing kvalue, k, , o. callback.call(t, kvalue, k, o); } // d. increase k 1. k++; } // 8. return undefined }; }
copied verbatim, reference (below) mdn foreach()
article; 01/04/2013, @ 14:30.
references:
Comments
Post a Comment