例如我有这个数组:
$scope.records = [ { "Name" : "Alfreds Futterkiste", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "Country" : "Mexico" }, { "Name" : "Ernst Handel", "Country" : "Austria" } ];
如何从对象获取价值指数?例如“ Country”:“ Austria”,该指数为3
您可以Array.findIndex在最新的浏览器中使用,但Internet Explorer中不支持此功能,只有Edge
Array.findIndex
let $scope = {}; $scope.records = [ { "Name" : "Alfreds Futterkiste", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "Country" : "Mexico" }, { "Name" : "Ernst Handel", "Country" : "Austria" } ]; let index = $scope.records.findIndex( record => record.Country === "Austria" ); console.log(index); // 3
为了在IE9及更高版本中提供支持,您可以Array.some改用
Array.some
var $scope = {}; $scope.records = [{ "Name": "Alfreds Futterkiste", "Country": "Germany" }, { "Name": "Berglunds snabbköp", "Country": "Sweden" }, { "Name": "Centro comercial Moctezuma", "Country": "Mexico" }, { "Name": "Ernst Handel", "Country": "Austria" }]; var index = -1; $scope.records.some(function(obj, i) { return obj.Country === "Austria" ? index = i : false; }); console.log(index);