[英]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.