olivier olivier - 10 days ago 5
AngularJS Question

Using the length function returns undefined

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?

Answer

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);

Comments