(AngularJS)如何遍历数组

时间:2014-09-17 08:25:08

标签: javascript arrays angularjs

这是php.i上的一个数组已经在json(使用json_encode)

中对其进行了转换
Array
(
    [codehttp] => Array
        (
            [0] => 200
            [1] => 200
            [2] => 200
            [3] => 200
        )

    [time] => Array
        (
            [0] => 2014-09-15 13:54:04
            [1] => 2014-09-15 13:54:04
            [2] => 2014-09-15 13:54:04
            [3] => 2014-09-15 13:54:04
        )

    [channel] => Array
        (
            [0] => channel1
            [1] => channel1
            [2] => channel1
            [3] => channel1
            [4] => channel1
        )

    [type] => Array
        (
            [0] => android
            [1] => android
            [2] => android
            [3] => android
            [4] => android
        )

    [indice] => Array
        (
            [0] => masterplaylist
            [1] => video_110000
            [2] => video_190000
            [3] => video_300000
            [4] => video_500000
        )

    [cdn] => Array
        (
            [0] => cdn1
            [1] => cdn1
            [2] => cdn1
            [3] => cdn1
            [4] => cdn1
        )

)

请问我想知道如何在javascript中解析最终的json变量(codehttp字段)。我想把它变成一个angularjs控制器。

我已尝试过这段代码(在控制器中),但它确实无法正常工作

$scope.flag_a = 'good';

for(var key in $scope.content.codehttp)
{
        if($scope.content.codehttp[key] != '200')
        {
                $scope.flag_a = 'bad';
        }
}

1 个答案:

答案 0 :(得分:11)

首先,您需要确保,您的响应实际上被视为JSON(从而产生正确的javascript对象),然后您可以使用以下三种方式:

使用angularjs自己的方法angular.forEach

$scope.content = {};
$scope.content.codehttp = [200, 200, 200, 201];

angular.forEach($scope.content.codehttp, function(value, key) {
  if (value != 200) {
    $scope.flag_a = 'bad';
  }
})

使用普通'for'循环:

for(i=0;i<$scope.content.codehttp.length;i++) { 
  if ($scope.content.codehttp[i] != 200) {
    $scope.flag_a = 'bad';
  }
}

使用(相对较新的)原生Array.prototype.forEach方法:

$scope = {};
$scope.content = {};
$scope.content.codehttp = [200, 200, 200, 201];

$scope.content.codehttp.forEach(function(value, key) {
    if (value != 200) {
        // for demonstrational purposes only:
        document.write("Entry #"+(key+1)+" contained a bad status: "+value);
        $scope.flag_a = 'bad';
    }
})