繁体   English   中英

如何在JavaScript中获取数组格式?

[英]How to get array format in javascript?

我在带有工厂功能的AngularJs中得到一个数组。 这是控制台

Array[0]
  0: "value1"
  1: "value2"
  length:2

但是当我想获取数组的长度时

console.log(array.length)

在回送中从mysql获取数据

 app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    } 
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});

控制器看起来像:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])

我知道长度为0。为什么呢?

这是一个时间问题。 第一次要求输入长度时,确实为0,但是几秒钟后使用Chrome Dev Tools检查对象时,您正在检查的是已填充的活动对象。

您可以使用setTimeout确认这一点

setTimeout(function(){
   console.log(array);
}, 0)

您可以查看此链接以获取更多说明

UPDATE

在angular中,使用$timeout而不是setTimeout 像这样:

$timeout(function(){
   console.log(array);
}, 0)

JavaScript中Array的length属性是不可变的。 您可以通过定义其中有多少个属性来设置数组的大小:var a = new Array(2),或仅传入值:var a = ['value1','value2']。

您可以在此处将异步与同步方法混合使用。

Communications.find是异步的,但您可以在getCommi使用它,例如同步功能。

调用getCommi该函数立即返回空array

请根据以下内容进行更改。

app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id, cb){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    } 
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    cb(null, array);
        });   
      }
  }
});

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
getFoo.getCommi(3,1, function(err, emails){
  $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
});    
}])

免责声明 :我不懂棱角。

尝试这个,

console.log(array[0].length)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM