【问题标题】:angular.foreach function throws syntax errorangular.foreach 函数抛出语法错误
【发布时间】:2014-08-06 16:53:11
【问题描述】:

函数 getTotal.getValues() 是一个返回“一”、“二”、“三”...“九”的服务器调用。我可以用 console.log(res) 打印它们。但是,似乎我无法将它们推入在 runTest 函数中创建的变量 v 中。在此代码中,console.log(r) 不打印任何内容,因为 return v 为空。有什么想法吗?

var test = [1,2,3,4,5,6,7,8,9];

        function runTest(val) {
            var v = [];
            val.forEach(function(t) {
                getTotal.getValues(t).then(function(res) {
                    //console.log(res);
                    v.push(res);
                });
            });
            return v;
        }
        runTest(test).forEach(function(r) {
            console.log(r);
        });

【问题讨论】:

  • 你的语法对我来说看起来不错。你确定这是你得到的语法错误吗?
  • 是的,我仍然遇到同样的错误。语法错误,$injector 无法启动 ...
  • 如果是语法错误,它会说类似SyntaxError: Unexpected token。上面的代码不能产生您报告的错误。
  • 好的,迈克,这是我在控制器外部的一个函数中设置我的测试变量,然后返回结果并在控制器中抓取它,语法错误消失了。我还有一个问题,让我更新我的问题...
  • 我在您提示后编辑了问题,这就是我的意思是 foreach 不起作用的地方。 v.push(res) 似乎不起作用,但是我可以使用 console.log(res) 打印 res 值

标签: javascript arrays angularjs for-loop foreach


【解决方案1】:

你是不是在 angular forEach 和 javascript forEach 之间搞错了。

Angular forEach 应该是这样的。我看不到你的代码 sn-p 的角度。

angular.forEach(test, function(value, key) {
    console.log(value);
});

【讨论】:

    【解决方案2】:

    这就是你的 forEach 函数的样子:

    var test = [1,2,3,4,5,6,7,8,9];
    test.forEach(function logArrayElements(element, index, array) {
        console.log("a[" + index + "] = " + element);
    });
    // logs:
    // a[0] = 1
    // a[1] = 2
    // a[2] = 3
    

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    但是如果要使用angular.forEach(),请参考: https://docs.angularjs.org/api/ng/function/angular.forEach

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 2019-11-15
      • 2017-12-13
      • 2016-10-31
      • 2023-03-20
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多