Array.indexOf , padLeft , padRight

พูดคุย แลกเปลี่ยน ปัญหา การเขียน JavaScript เครื่องมือ AJAX Web 2.0 AJAX Framework Jquery

Moderator: mindphp

User avatar
jataz2
PHP Super Member
PHP Super Member
Posts: 235
Joined: 22/02/2011 11:48 am

Array.indexOf , padLeft , padRight

Post by jataz2 » 28/06/2019 11:16 am

Code: Select all

//Example Array IndexOf
             var arrProduct = new Array();
             arrProduct.push("TH");
             arrProduct.push("EN");
             var ind = arrProduct.indexOf("EN");
             if (ind > -1) {
                 arrProduct.splice(ind, 1);
             }      

//Example padLeft
     var n = 123;
     var s = n.toString().padLeft("0", 5);    output --> s="00123"

//Example padRight
    var n = 123;
    var s = n.toString().padRight("0", 5);    output --> s="12300"

copy code prototype ด้านล่างนี้ไปแปะในไฟล์ .js ก็เรียกใช้งานได้แล้วครับ

Code: Select all

 if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (what, i) {
            i = i || 0;
            var L = this.length;
            while (i < L) {
                if (this[i] === what) return i;
                ++i;
            }
            return -1;
        };
    }

String.prototype.padLeft = function (paddingChar, length) {

    var s = new String(this);

    if ((this.length < length) && (paddingChar.toString().length > 0)) {
        for (var i = 0; i < (length - this.length) ; i++)
            s = paddingChar.toString().charAt(0).concat(s);
    }

    return s;
};

String.prototype.padRight = function (paddingChar, length) {

    var s = new String(this);

    if ((this.length < length) && (paddingChar.toString().length > 0)) {
        for (var i = 0; i < (length - this.length) ; i++)
            s = s.concat(paddingChar.toString().charAt(0));
    }

    return s;
};

  • Similar Topics
    Replies
    Views
    Last post

Return to “JavaScript & Jquery Ajax”

Who is online

Users browsing this forum: No registered users and 34 guests