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

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

问题描述

假设我是一名用户脚本开发人员并且我无法控制页面上的 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 不是它的一部分,所以你不需要在 arr 中测试 3.

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( ( _, i ) => i in arr );

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

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