Javascript 未捕获的类型错误:rand.slice 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30273220/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: rand.slice is not a function
提问by Red Virus
I'm getting the following error on browser console
我在浏览器控制台上收到以下错误
Uncaught TypeError: rand.slice is not a function
未捕获的类型错误:rand.slice 不是函数
JavaScript
JavaScript
var rand, date;
date = Date.now();
rand = Math.random() * Math.random();
rand = Math.floor(date * rand);
rand = rand.slice(-5); 
document.getElementById("test").innerHTML = rand;
I'm not able to figure it out what's wrong with this code.
我无法弄清楚这段代码有什么问题。
回答by Dyrandz Famador
you can't directly slice a number.. you can convert to string first then sliceafter
你不能直接切了一些..你可以转换为字符串,然后先slice后
like this:
像这样:
rand = rand.toString().slice(-5)
JavaScript Array slice() Method
回答by Ramanathan Muthuraman
Try using rand = rand.toString().slice(-5);instead of rand = rand.slice(-5);
尝试使用rand = rand.toString().slice(-5);代替rand = rand.slice(-5);
slicecan be used either on arrayor stringand not on numbers.
slice可用于array或string不用于数字。
回答by Yangguang
try:
尝试:
rand = (rand+'').slice(-5); 

