str_shuffle() equivalent in javascript?

☆樱花仙子☆ 提交于 2019-12-01 22:14:11

问题


Like the str_shuffle() function in PHP, is there a function similar in shuffling the string in javascript ?

Please help !


回答1:


No such function exist, you'll write one yourself. Here's an example:

function shuffle(string) {
    var parts = string.split('');
    for (var i = parts.length; i > 0;) {
        var random = parseInt(Math.random() * i);
        var temp = parts[--i];
        parts[i] = parts[random];
        parts[random] = temp;
    }
    return parts.join('');
}

alert(shuffle('abcdef'));



回答2:


You could use php.js implementation: http://phpjs.org/functions/str_shuffle:529




回答3:


No, there is no inbuilt method of String that will randomise the character sequence.




回答4:


Here's my versinof the php.js function

function str_shuffle (str) {

    var newStr = [];

    if (arguments.length < 1) {
        throw 'str_shuffle : Parameter str not specified';
    }

    if (typeof str !== 'string') {
        throw 'str_shuffle : Parameter str ( = ' + str + ') is not a string';
    }

    str = str.split (''); 
    while (str.length) {
        newStr.push (str.splice (Math.floor (Math.random () * (str.length - 1)) , 1)[0]);
    }

    return newStr.join ('');
}



回答5:


You could also do it as a prototype:

String.prototype.shuffle = function() {
  var parts = this.split('');

  for (var i = 0, len = parts.length; i < len; i++) {
    var j = Math.floor( Math.random() * ( i + 1 ) );
    var temp = parts[i];
    parts[i] = parts[j];
    parts[j] = temp;
  }

  return parts.join('');
};

Using it like so:

var myString = "Hello";
myString = myString.shuffle();



回答6:


I would recommend lodash shuffle function.

const result = _.shuffle('my_string');


来源:https://stackoverflow.com/questions/3079385/str-shuffle-equivalent-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!