admin管理员组文章数量:1337731
let m = 5;
m = m.padStart(2, '0');
Error:
m.padStart is not a function
Expecting result: 05
;
I'm on Chrome, last version.
Any help?
let m = 5;
m = m.padStart(2, '0');
Error:
m.padStart is not a function
Expecting result: 05
;
I'm on Chrome, last version.
Any help?
Share Improve this question edited Mar 14 at 14:53 TylerH 21.1k78 gold badges79 silver badges114 bronze badges asked Jan 5, 2019 at 8:17 qadenzaqadenza 9,30118 gold badges78 silver badges144 bronze badges 2-
1
Numbers do not have a
padStart
method. – CertainPerformance Commented Jan 5, 2019 at 8:17 - It's a string method, so if you want to use it, cast the number to a string. – CertainPerformance Commented Jan 5, 2019 at 8:21
4 Answers
Reset to default 20The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
It is a String function. Not a number function. Refer
Solution-
let m = '5';
m = m.padStart(2, '0');
alert(m)
Convert your value from int
to String
just like this int.toString().padStart(n, '0');
change the number value to string , I was need this function to convert current hour value to leading zero number , your example should be
let m = 5+''; // just in case you can't change the actual number variable .
m = m.padStart(2, '0');
my code that i was need it
function CurrentTime( ) {
var today = new Date();
var h = today.getHours( )+'' ; var m = today.getMinutes()+'' ;
return h.padStart( 2 , '0' ) +':'+m.padStart( 2 , '0' ) ;
}
var current = CurrentTime( ) ;
var timeNow = mydiv.innerText ; console.log("current: " + current) ;
Since padStart()
is not patible with Internet Explorer (IE) and other old browser versions and if you try using it with numbers you can get:
let m = 5;
m = m.padStart(2, '0');
alert(m);
Uncaught TypeError: m.padStart is not a function at :2:7
Here I am to provide you a function that I created, it works fine with Strings as well as Numbers in case that somebody need something like that padding a Number to 01, 02, .. 09:
let m = 5;
m = padValue(m);
alert(m);
// Sam pading value to start with 0. eg: 01, 02, .. 09, 10, ..
function padValue(value) {
return (value < 10) ? "0" + value : value;
}
As I mentioned you can replace assigned 5 value to 05:
let m = '5'; // The result will be 05
If you pass a value greater than 9 as String or Number will display the value without adding the padding. e.g.:
let m = '10'; // The result will be 10
Or
let m = 10; // The result will be 10
版权声明:本文标题:javascript - Why do I get "padStart is not a function" when using padStart on numbers? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743496589a2494361.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论