【问题标题】:(AngularJS) how to loop through an Array(AngularJS)如何循环遍历数组
【发布时间】:2014-11-11 04:48:09
【问题描述】:

这是 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 中解析(codehttp 字段)最终的 json 变量。我想把它做成一个 angularjs 控制器。

我已经尝试过这段代码(在控制器中),但它不起作用

$scope.flag_a = 'good';

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

【问题讨论】:

  • for...in 循环用于对象,而不是数组,使用for(i=0;i<$scope.content.codehttp.length;++i) 表示数组

标签: javascript arrays angularjs


【解决方案1】:

首先您需要确保您的响应实际上被视为 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
  • 很好的补充,减去了 alert()
  • 将警报更改为同样丑陋的document.write,以提供一些关于工作代码的反馈。 (抱歉编辑了这么多,只是想试试新的代码sn-p功能:-D)
猜你喜欢
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多