如何区分未定义的数组元素和空槽? [英] How to tell between undefined array elements and empty slots?

查看:75
本文介绍了如何区分未定义的数组元素和空槽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我是一名用户脚本开发人员,我无法控制页面上的javascript。该页面创建具有随机长度的数组,用随机值填充它们(包括虚假的值,例如 undefined )。并非每个元素都必须赋值,因此可能会有空插槽。

Suppose I am a user script developer and I don't have control over the on-page javascript. The page creates arrays with random lengths, filling them with random values (including falsy ones, such as undefined). Not every element has to be assigned a value, so there may be empty slots.

简化示例(Firefox控制台):

A simplified example (Firefox console):

var arr = new Array(3);
arr[0] = null;
arr[1] = undefined;
console.log(arr);               \\ Array [ null, undefined, <1 empty slot> ]
console.log(arr[1]);            \\ undefined
console.log(arr[2]);            \\ undefined
console.log(arr[1] === arr[2]); \\ true
console.log(typeof arr[1]);     \\ undefined
console.log(typeof arr[2]);     \\ undefined

正如我们所见,Firefox显示 undefined 和空插槽不同,而对于javascript他们似乎是相同的。

As we can see, Firefox displays undefined and empty slots differently, whereas for javascript they seem to be identical.

现在假设我要清理这样的数组,删除所有空插槽但离开 undefined 元素完好无损。我该怎么做?

Now suppose I want to clean such an array, removing all empty slots but leaving undefined elements intact. How do I do that?

推荐答案

你可以使用 in 运算符,检查数组是否有密钥。对于空插槽,它将返回false,但对于包含值的插槽,则为true,包括值 undefined

You can use the in operator to check if the array has a key. It will return false for empty slots, but true for slots with values, including the value undefined:

var arr = new Array(3);
arr[0] = null;
arr[1] = undefined;

1 in arr; // true
2 in arr; // false

请注意,您无法区分数组末尾的空插槽和插槽使用它,但如果你知道数组的长度,那么你已经知道 3 不是它的一部分,所以你不需要测试 3 in arr

Note that you can't distinguish between empty slots and slots past the end of the array using that, but if you know the length of the array, then you already know that 3 isn't part of it, so you don't need to test 3 in arr.

你也可以过滤掉这样的空位:

You can also filter out the empty slots like this:

arr = arr.filter( function ( _, i ) { return i in arr } );

这篇关于如何区分未定义的数组元素和空槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆