简体   繁体   中英

Javascript code to same number many time

This php generate 0 ten or less times

str_repeat('0', mt_rand(1, 10))

how can i do it in javascript in html

i want only 0 many time

您可以使用“加入数组”技巧重复一个字符串,并使用Math.random()获取一个随机数,以及使用任何按位运算将数字四舍五入,因此一种简洁的方法是:

Array(Math.random() * 11 + 1 | 0).join('0')
// Function simulating PHP str_repeat()
function str_repeat(str, multiplier) {
  return new Array(multiplier + 1).join(str);
}

// Generate the string
var number_of_times = Math.floor(Math.random()*11);
var my_repeated_string = str_repeat('0', number_of_times);

// Put the string inside a HTML element
document.getElementById("your_element_id").innerHTML = my_repeated_string;

Ok here goes...

var $yourString;

for(var i=0;i<10;i++) { 
  $yourString += "0"; 
}

Is that what you are trying to do? Your comment on the other answer says you want to generat 0 many times, not random number. This will do that and build it into one string. Not sure why you would do that.

Hope this helps!

I like the array join hack (upvoted it), but here's a functional way:

function str_repeat (str, n) {
    n = parseInt(n, 10);

    if (--n) {
        str += str_repeat(str, n);
    }

    return str;
}


console.log(str_repeat('0', 10));  // 0000000000

Reusable parts:

function GetRandom(min, max)
{
    return Math.round(Math.random() * (max - min)) + min;
}

function CreateRandomRepeat(text, min, max)
{
    var repeat = [];

    for (var index = 0; index < GetRandom(min, max); index++)
    {
        repeat[index] = text;
    }

    return repeat.join('');
}

Solution:

CreateRandomRepeat('0', 1, 10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM