使用Array中存在的对象提取数组

时间:2017-01-23 08:51:26

标签: javascript arrays firebase

我正在使用firebase数据库。

删除对象后,快照将返回一个长度超过实际数组值的数组:

fireBase.ref(REFS_CATEGORIES_ONE_TIMERS).once('value', function (snapshot) {
            const values = snapshot.val(); // This array will contain 2 valus with leanth of 3
            returnFunc(extract);
 });

数组内容:

myArray[0] : SomeObject;
myArray[2] : SomeObject;

当循环遍历此数组时,它将循环3次,并且该值将是未定义的。

如何删除缺失的条目以更优雅的方式而不是循环播放?

3 个答案:

答案 0 :(得分:3)

Array.prototype.filter函数只处理数组中存在键的元素,因此使用始终返回true的回调调用该元素就足够了:

var extract = myarray.filter(_ => true);

生成的数组将具有连续的索引,删除缺少的条目以及任何后续条目"折叠"进入他们留下的空隙。

答案 1 :(得分:1)

您可以使用in来测试索引是否在数组中。

for (var i = 0; i < array.length; i++) {
    if (i in array) {
        // do something with array[i]
    }
}

答案 2 :(得分:-1)

以下是3种方法,我试过了。

var UNDEFINED = undefined;
var UNDEFINED_STR = 'undefined';

var sampleWithOutEmpty = [10, 'hello', null, {}];
var sampleWithEmpty = [, 10, 'hello', , null, {}];

function allAllSlotsFilled (sample){
	/* 
	 1.
	 check if filtered values that are NOT UNDEFINED is equal to the length of the orignal array ... 
	 if the lenghts aren't same then the array EMPTY slots.
	*/
	var result = (sample.filter(element => { return typeof(element) !== UNDEFINED_STR;}).length  === sample.length);
	console.log(result);

	/* 	
	 2.
	 sort array in descending order. undefined gets pushed to the last. 
	 Then check if the last item is undefined.
	 if YES the array has empty slots.
	*/
	sample.sort()
	result = (typeof(sample[sample.length -1]) !== UNDEFINED_STR); 
	console.log(result);

	/*
	 3.
	 Using sets. Create a set with elements in array. Then check is UNDEFINED is a element in set.
	 If YES the array has empty slots.
	*/
	var set = new Set(sample);
	result = !set.has(UNDEFINED);
	console.log(result);

}

allAllSlotsFilled(sampleWithOutEmpty);
allAllSlotsFilled(sampleWithEmpty);