Reputation: 2645
I'm trying to check if my variable only has a length of one.
I do this like so:
var n = new Date();
$scope.h = n.getHours();
$scope.m = n.getMinutes();
console.log($scope.h.length) // returns undefined
if($scope.h.length < 2 && $scope.m.length < 2 ) {
$scope.hm = $scope.h * 10 + "" + $scope.m * 10;
console.log($scope.hm);
}
but $scope.h.length returns undefined. Why? How should i do this better?
Upvotes: 1
Views: 774
Reputation: 93
getHours() returns a number. Numbers do not have a length property. Try converting your number to a string first with $scope.h.toString().
Upvotes: 0
Reputation: 357
You don't need to check length in your case.
if($scope.h < 10 && $scope.m < 10 ) {
Upvotes: 3
Reputation: 13943
You were using Date.prototype.getHours()
thta return an integer number
thus you cannot directly use .length
on it.
The solution is to use the toString()
function before taking the length
OR
You can use = "" + h
var n = new Date();
var h = n.getHours();
var m = n.getMinutes();
var hString = "" + h;
var mString = m.toString();
console.log(hString.length);
console.log(mString.length);
Upvotes: 3