Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - How to tell between undefined array elements and empty slots?

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.

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...