Javascript 如何在AngularJS中获取数组中的最后一条记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28741842/
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
How to get the last record in an array in AngularJS
提问by Besa
I have an array of objects ObjectsArr= [Object1 , Object2,Object3, Object4]I want to show in my view the last object, how to do that in angularjs?
我有一组对象,ObjectsArr= [Object1 , Object2,Object3, Object4]我想在我的视图中显示最后一个对象,如何在 angularjs 中做到这一点?
回答by Vinay K
ObjectsArr[ObjectsArr.length - 1]-- this will give you the last element in the array.
To display it in view: {{ObjectsArr[ObjectsArr.length - 1]}}
ObjectsArr[ObjectsArr.length - 1]-- 这将为您提供数组中的最后一个元素。
要在视图中显示它:{{ObjectsArr[ObjectsArr.length - 1]}}
This will work even when the array has zero entries.
即使数组有零个条目,这也将起作用。
回答by sylwester
You can use ng-if directive and check if element is last by:
您可以使用 ng-if 指令并通过以下方式检查元素是否最后:
ng-if="$last"
please see demo below
请看下面的演示
var app = angular.module('app', ['ui.bootstrap']);
app.controller('homeCtrl', function ($scope) {
$scope.data = [1,2,3]
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body >
<div ng-app="app">
<div ng-controller="homeCtrl">
<ul>
<li ng-repeat="item in data" ng-if="$last">{{item}}</li>
</ul>
</div>
</div>
</body>
</html>
回答by Or Guz
For working with Arrays I recommend Lodashor Underscore. It will save you a lot of time in the future.
对于使用数组我建议Lodash或下划线。它会在未来为您节省很多时间。
Both have last method:
两者都有最后一种方法:
_.last([1, 2, 3]); //Will return 3
See the links for API and installation.
请参阅 API 和安装链接。
As for viewing the result in the view, you can assign a scope variable in the relevant controller for the result and show it.
至于在视图中查看结果,可以在相关控制器中为结果分配一个作用域变量,并显示出来。
Controller:
控制器:
$scope.lastItem = _.last(array);
View:
看法:
{{lastItem}}
回答by Hossein Aghatabar
you can use reverse!
你可以使用反向!
count = [0,1,2,3]
count.reverse()
//[3,2,1,0]
count[0];
// 3

