检查数组是否在AngularJs中具有特定索引

时间:2017-02-18 09:37:08

标签: javascript html angularjs arrays angularjs-scope

在AngularJS表达式中,如何检查数组是否在特定索引中具有值?请考虑以下示例

$scope.arr =['one','two','three'];

在HTML中。

<p ng-show="arr[3]!=''">{{arr[3]}}</p>

2 个答案:

答案 0 :(得分:3)

您必须与undefined进行比较。

<p ng-show="arr[3]!=undefined">{{arr[3]}}</p>

function MyCtrl($scope) {
  $scope.arr =['one','two','three'];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
       <p ng-show="arr[2]!=undefined">{{arr[2]}}</p>
  </div>
</div>

此外,您可以使用function运算符定义particular,以检查数组是否在typeof索引中具有值。

function isDefined(arrayElement) {
      return typeof arrayElement!== 'undefined';
}

function MyCtrl($scope) {
  $scope.arr =['one','two','three'];
  $scope.isDefined=function(arrayElement){
      return typeof arrayElement!== 'undefined';
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
       <p ng-show="isDefined(arr[3])">{{arr[3]}}</p>
       <p ng-show="!isDefined(arr[3])">undefined</p>
  </div>
</div>

答案 1 :(得分:0)

您可以直接在ng-show中传递带索引的数组。因为当您使用ng-show="arr[index]"时,如果array中存在true,那么array如果undefined中不存在具有特定索引的值,则它将为false {1}}即function MyCtrl($scope) { $scope.arr =['one','two','three']; } ..

参见此示例

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
       <p ng-show="arr[2]">{{arr[2]}}</p>
       <p ng-show="arr[3]">{{arr[3]}}</p>
  </div>
</div>
&#13;
pointer-events
&#13;
&#13;
&#13;