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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:53:59  来源:igfitidea点击:

Uncaught TypeError: rand.slice is not a function

javascript

提问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

JavaScript 数组 slice() 方法

JavaScript String slice() method

JavaScript String slice() 方法

回答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可用于arraystring不用于数字。

回答by Yangguang

try:

尝试:

rand = (rand+'').slice(-5);