Maison  >  Article  >  interface Web  >  Méthode JavaScript pour implémenter StringBuffer dans les compétences Java_javascript

Méthode JavaScript pour implémenter StringBuffer dans les compétences Java_javascript

WBOY
WBOYoriginal
2016-05-16 16:15:061887parcourir

L'exemple de cet article décrit comment JavaScript implémente StringBuffer en Java. Partagez-le avec tout le monde pour votre référence. Les détails sont les suivants :

L'implémentation de la classe Javascript StringBuffer consiste à construire une classe StringBuffer via un prototype, le code est le suivant :

function StringBuffer() {
  this.__strings__ = new Array();
}

StringBuffer.prototype.append = function(str) {
  this.__strings__.push(str);
};

StringBuffer.prototype.toString = function() {
  return this.__strings__.join("");
};

Exemple :

<html>
<head>
<title>test</title>
<script type="text/javascript">
    function StringBuffer() {
      this.__strings__ = new Array();
    }
    StringBuffer.prototype.append = function(str) {
      this.__strings__.push(str);
    };
    StringBuffer.prototype.toString = function() {
      return this.__strings__.join("");
    };

    function testStringBuffer(){
       var date1 = new Date();
       var str;
       for( var i=0; i<10000; i++){
         str += "text";
       }
       var date2 = new Date();
       document.writeln("Sting use time:"+ (date2 - date1) +"ms");

       //StringBuffer
       var date3 = new Date();
       var strBuffer = new StringBuffer();
       for(i=0; i<10000; i++){
         strBuffer.append("text");
       }
       strBuffer.toString();
       var date4 = new Date();
       document.writeln("<br/>StringBuffer use time:"+ (date4 - date3) +"ms");
    }
</script>
</head>
<body>
   <input type="button" value="testStringBuffer" onclick="testStringBuffer()"/>
</body>
</html>

J'espère que cet article sera utile à la conception de la programmation JavaScript de chacun.

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn