(AngularJS) 如何遍历一个数组

5

这是一个 PHP 数组。我已将其转换为 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中解析(代码http字段)最终的JSON变量?我想在AngularJS控制器中实现它。以下是我在控制器中尝试过的代码,但它无法正常工作:
$scope.flag_a = 'good';

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

4
for...in 循环适用于对象,不适用于数组。如果要遍历一个数组,请使用 for(i=0;i<$scope.content.codehttp.length;++i) - Elias Van Ootegem
1个回答

12

首先,您需要确保您的响应实际上被视为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';
    }
})


缺失 Array.prototype.forEach - Christoph
不错的加法,去掉alert()。 - Nitsan Baleli
1
将警告更改为类似丑陋的 document.write,以提供工作代码的一些反馈。(对于如此频繁地编辑,很抱歉,我只是想尝试一下新的代码片段功能:-D) - Christoph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接