Sihem Hcine
Sihem Hcine

Reputation: 1129

Error in getting the last element of array

I have to log the last element in an array. I try this code:

       $scope.t=["item1","item2","item3"];
       $scope.tablng= $scope.t.length ; 
       console.log( $scope.t[$scope.tablng]); 

But i get undefined. How can i fix it please

Upvotes: 0

Views: 311

Answers (3)

Nguyễn Jason
Nguyễn Jason

Reputation: 1

when you get first item in array : array[0]
get last item in array: array[length-1]
In you code:

console.log( $scope.t[$scope.tablng-1]);

Upvotes: 0

Hitesh Kumar
Hitesh Kumar

Reputation: 3698

You can write your prototype function:

Array.prototype.last=function(){
return this[this.length-1];
};

$scope.t=["item1","item2","item3"];
console.log($scope.t.last()); //"item3"

Upvotes: 0

user6383968
user6383968

Reputation: 71

In array, index are starting from 0, so you have to minus 1 to the length you retrieved to get the last element in array. A quick fix will be

$scope.t=["item1","item2","item3"];
$scope.tablng = $scope.t.length; 
console.log( $scope.t[$scope.tablng-1]); 

An even better approach, is to also determine if the array is empty, because in that case $scope.tablng will be -1, which is again undefined

$scope.t=["item1","item2","item3"];
if ($scope.t.length > 0) {
   $scope.tablng = $scope.t.length-1; 
   console.log( $scope.t[$scope.tablng]); 
} else {
   // the array is empty
}

JSFiddle: https://jsfiddle.net/56jyjjwt/1/

Upvotes: 2

Related Questions