【问题标题】:Extract Array with objects that exists from Array使用 Array 中存在的对象提取 Array
【发布时间】:2017-01-23 08:51:25
【问题描述】:

我正在使用 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次,到时候值会是未定义的。

我怎样才能以一种比循环更“优雅”的方式删除丢失的条目

【问题讨论】:

  • 我已经尝试循环和签入 undefined,但我正在寻找更好的选择
  • 投票重新开放 - 问题陈述很明确
  • @MCMatan 我稍微重新编辑了这个问题,因为您编辑的版本所写的“未定义值”和“缺少的条目”之间存在非常明显(且重要)的语义差异”。 myArray[1] 有可能实际持有 undefined 的值,但此时它不再严格缺失。
  • @Alnitak 感谢您的通知????

标签: javascript arrays firebase


【解决方案1】:

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

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

生成的数组将具有连续的索引,缺失的条目将被删除,任何后续条目“折叠”到它们留下的间隙中。

【讨论】:

  • 当不需要参数时,_ 是否比 () 更好?
  • @UlysseBN 我不会争辩说它是“最好的”,但它并不比使用e => true 而忽略e 的值更差,并使用_ 的通用语义来表示未使用的变量,它也比() =>短。
【解决方案2】:

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

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

【讨论】:

  • 此语法也适用:for (i in array) { doStuffWith = a[i] }
  • @UlysseBN 在数组上使用for .. in 是不受欢迎的,因为它还会遍历数组的任何可枚举的非数字属性。
  • 对。我从 Array.prototype.filter MDN 页面中的 polyfill 获得了这种方法。
  • @Barmar 是的,这也是我知道filter 可以用来执行此操作的原因:)
【解决方案3】:

以下是我尝试过的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);

【讨论】:

  • OP 不想知道 if 数组缺少键,他想要一个连续的没有任何缺少键的新副本。此外,您拥有的代码会查找未定义的,而不是缺少键。 [0,,2][0, undefined, 2] 之间存在语义差异。在后者中,键 1 确实存在,但具有 undefined 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2014-09-30
  • 2019-06-13
相关资源
最近更新 更多