peterS.: gesamtlänge aller string-typen eines arrays

Beitrag lesen

gruss Siechfred, hi Cheatah, hallo Paul,

Erweitere den Prototypen von Arrays um eine getContentLength()-
Methode (o.ä.), die dies ermittelt.

Cheatah

... code ...
Ausbaufähig, denke ich :)

Siechfred

kurz und schmerzlos ueber [Array.filter] und [Array.join]:

~~~javascript Array.prototype.getStringTypesLength = function () {

return (this.filter(function (elm) {return ((typeof elm == "string") || (elm instanceof String))}).join("").length);
  };
/*

test it:

Array.prototype.getStringTypesLength = function () {return(this.filter(function(elm){return((typeof elm=="string")||(elm instanceof String))}).join("").length);};

alert(["hallo", "welt", {}, [], , "", 1, (new String("Baum")), "Haus", Number.NaN, String(42)].getStringTypesLength()); // 19;
*/
//javascript:Array.prototype.getStringTypesLength = function () {return(this.filter(function(elm){return((typeof elm=="string")||(elm instanceof String))}).join("").length);};alert(["hallo", "welt", {}, [], , "", 1, (new String("Baum")), "Haus", Number.NaN, String(42)].getStringTypesLength());

  
  
  
oder aber \*old school\*-maessig:  
  
  
  ~~~javascript
Array.prototype.getStringTypesLength = function () {  
  
    var i, obj, arr = [];  
    for (i = 0; i<this.length; ++i) {  
  
      obj = this[i];  
      if ((typeof obj == "string") || (obj instanceof String)) {  
  
        arr.push(obj);  
      }  
    }  
    return arr.join("").length;  
  };  
/*  
  test it:  
  
  Array.prototype.getStringTypesLength = function () {var i,obj,arr=[];for(i=0;i<this.length;++i){obj=this[i];if((typeof obj=="string")||(obj instanceof String)){arr.push(obj);}}return arr.join("").length;};  
  
  alert(["hallo", "welt", {}, [], , "", 1, (new String("Baum")), "Haus", Number.NaN, String(42)].getStringTypesLength()); // 19;  
*/  
//javascript:Array.prototype.getStringTypesLength = function () {var i,obj,arr=[];for(i=0;i<this.length;++i){obj=this[i];if((typeof obj=="string")||(obj instanceof String)){arr.push(obj);}}return arr.join("").length;};alert(["hallo", "welt", {}, [], , "", 1, (new String("Baum")), "Haus", Number.NaN, String(42)].getStringTypesLength());

so long - peterS. - pseliger@gmx.net

--
»Because objects in JavaScript are so flexible, you will want to think differently about class hierarchies.
Deep hierarchies are inappropriate. Shallow hierarchies are efficient and expressive.« - Douglas Crockford
ie:( fl:) br:> va:( ls:& fo:) rl:| n3;} n4:} ss:} de:µ js:} mo:? zu:]