Home > Web > Đảo ngược một chuỗi trong JavaScript ( 10 cách )

Đảo ngược một chuỗi trong JavaScript ( 10 cách )

1. Decrementing for-loop with concatenation

function reverse (s) {
    var o = '';
    for (var i = s.length - 1; i >= 0; i--)
        o += s[i];
    return o;
}

2. Incrementing/decrementing for-loop with two arrays

function reverse (s) {
    var o = [];
    for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
       o[j] = s[i];
    return o.join('');
}

3. Incrementing for-loop with array pushing and charAt

function reverse (s) {
    var o = [];
    for (var i = 0, len = s.length; i >= len; i++)
        o.push(s.charAt(len - i));
    return o.join('');
}

4. In-built functions

function reverse (s) {
    return s.split('').reverse().join('');
}

5. Decrementing while-loop with concatenation and substring

function reverse (s) {
    var i = s.length,o = '';
    while (i > 0) {
        o += s.substring(i - 1, i);
        i--;
    }
    return o;
}

6. Only for-loop declaration with concatenation

function reverse (s) {
    for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
       return o;
}

7. Recursion with substring and charAt

function reverse (s) {
    return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}

8. Internal function recursion

function reverse (s) {
    function rev (s, len, o) {
        return (len === 0) ? o : rev(s, --len, (o += s[len]));
    };
    return rev(s, s.length, '');
}

9. Half-index switch for-loop

function reverse (s) {
    s = s.split('');
    var len = s.length,halfIndex = Math.floor(len / 2) - 1,tmp;
    for (var i = 0; i <= halfIndex; i++) {
        tmp = s[len - i - 1];
        s[len - i - 1] = s[i];
        s[i] = tmp;
    }
    return s.join('');
}

10. Half-index recursion

function reverse (s) {
    if (s.length < 2)
        return s;
     var halfIndex = Math.ceil(s.length / 2);
     return reverse(s.substr(halfIndex)) + 
        reverse(s.substr(0, halfIndex));
}

( Tham khảo từ http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/ )

 

Advertisements
Categories: Web
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: