JQuery - 随机 .replace() 错误
JQuery - random .replace() error
我对随机.replace()有问题,它都显示相同的随机数,我正在尝试用不同的随机数替换$random$。
$(document).ready(function() {
var arr = [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10'
]
$("#present-users").children('li.present-user').each(function() {
arr.push($(this).find('img')[0].title);
});
var random = arr[Math.floor(Math.random() * arr.length)];
var text = "$random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$".replace(/'$random'$/g, random);
alert(text)
});
JSFIDDLE 示例
谢谢尼古拉
一种解决方案是使用 .replace(regex, function)
重载:
str.replace(/'$random'$/g, function() {
return arr[Math.floor(Math.random() * arr.length)];
});
更新的小提琴
你只调用了一次 Math.random(),并多次使用这个答案。
解决此问题的一种方法是使函数随机化,例如
var arr = [10,20,30];
var random = function(){return Math.floor(Math.random() * arr.length)};
alert(random());
alert(random());
alert(arr[random()]);
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 我使用了replace(“[^-A-Za-z0-9()%.],但它为'我可以解决这个错误吗
- Replace()产生“;未捕获的类型错误:未定义的不是函数“;当与零一起使用时
- 为什么我会得到错误“;未捕获的类型错误:st.replace不是函数;
- JavaScript String.replace()中的错误,替换字符串“”$'&”;
- 为什么使用 jQuery .replace 会导致网页找不到错误
- JQuery - 随机 .replace() 错误
- 错误:b.replace不是函数(以前从未得到过)
- 错误:text.replace不是angularjs过滤器中的函数,如何解决此问题
- 设置嵌套循环值返回错误“”;e.replace不是一个函数;
- Opera中的Javascript位置.replace错误
- 错误:TypeError: Cannot call method 'replace'的定义
- 错误:TypeError: Cannot call method 'replace'的定义
- TypeError: str.replace不是vue.js Ajax调用的函数奇怪错误
- .replace()不起作用.给出错误.replace不是一个函数
- 0x800a138f - JavaScript运行时错误:无法获取属性'replace'未定义或空引用的