簡體   English   中英

獲取firebase返回的數組的長度

[英]Get length of an array returned by firebase

數組的通常.length屬性不適用於firebase返回的數組。 這是返回數組的console.log:

0: Object
1: Object
2: Object
3: Object
4: Object
$$added: function () { [native code] }
$$error: function () { [native code] }
$$moved: function () { [native code] }
$$removed: function () { [native code] }
$$updated: function () { [native code] }
$add: function () { [native code] }
$destroy: function () { [native code] }
$getRecord: function () { [native code] }
$indexFor: function () { [native code] }
$inst: function () { [native code] }
$keyAt: function () { [native code] }
$loaded: function () { [native code] }
$remove: function () { [native code] }
$save: function () { [native code] }
$watch: function () { [native code] }
length: 5
__proto__: Array[0]
concat: function concat() { [native code] }
constructor: function Array() { [native code] }
every: function every() { [native code] }
filter: function filter() { [native code] }
findIndex: function (a){if(null==this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof a)throw new TypeError("predicate must be a function");for(var b,c=Object(this),d=c.length>>>0,e=arguments[1],f=0;d>f;f++)if(f in c&&(b=c[f],a.call(e,b,f,c)))return f;return-1}
forEach: function forEach() { [native code] }
indexOf: function indexOf() { [native code] }
join: function join() { [native code] }
lastIndexOf: function lastIndexOf() { [native code] }
length: 0
map: function map() { [native code] }
pop: function pop() { [native code] }
push: function push() { [native code] }
reduce: function reduce() { [native code] }
reduceRight: function reduceRight() { [native code] }
reverse: function reverse() { [native code] }
shift: function shift() { [native code] }
slice: function slice() { [native code] }
some: function some() { [native code] }
sort: function sort() { [native code] }
splice: function splice() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
unshift: function unshift() { [native code] }

甚至console.log length屬性顯示5但由於某種原因調用length屬性返回0。

編輯:

數組的length屬性設置為5,但proto的length屬性為0. .length屬性返回proto下的0值。

請記住,調用$asArray是一個異步操作。

$scope.notes = $firebase(ref).$asArray();
console.log($scope.notes.length); // the data has not loaded yet

您在控制台中看到零長度的原因是因為值可以在緩沖日志和打印之間發生變化,這可能會產生誤導。 嘗試使用斷點在執行時查看值。

由於數據是異步的,因此您需要使用$loaded promise。

$scope.notes.$loaded().then(function(notes) {
   console.log(notes.length); // data is loaded here
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM