如何使用angular js中的值获取范围数组的索引

时间:2015-04-18 06:35:57

标签: javascript angularjs

我有这样的$scope.arrSubThick = [1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 8, 7: 10, 8: 12, 9: 15, 10: 19]如何在脚本中获取此数组的键。

例如:值3的键是2,类似的第6个值键是5

提前致谢

2 个答案:

答案 0 :(得分:2)

JavaScript没有"关联数组"。它有数组:

[1, 2, 3, 4, 5]

或对象:

{1: 2, 2: 3, 3: 4, 4: 5, 5: 6}

第二种情况,就是你想要的,然后就可以使用:

    var looking_for = 3;
    var looking_for_key; 
    angular.forEach(values, function(value, key) {
        if(value == looking_for){
            looking_for_key = key;
        }
    });
   alert(looking_for_key);

答案 1 :(得分:0)

在js中无法定义类似的数组键。你可以通过使用对象数组来这样做:

 $scope.arrSubThick = [{1: 2}, {2: 3}, {3: 4}];

或者使用单个对象(我猜,这符合您的需求):

$scope.arrSubThick = {1: 2, 2: 3, 3: 4};
console.log($scope.arrSubThick[1]); // 2

如果要按值查找键,请执行以下操作:

$scope.arrSubThick = {
    1: 2,
    2: 3,
    3: 4
};
$scope.selected = null;
$scope.getItemByValue = function(value) {
    angular.forEach($scope.arrSubThick, function (val, key) {
        if (val == value) {
            $scope.selected = key;
        }
    });
};
$scope.getItemByValue(2);

http://plnkr.co/edit/smHJyRLsFk5GumuTGJQp?p=preview