質問

I have a sparse array; that is, an array in which some elements have been deleted. Elements are constantly being added and deleted from the middle, so it is very large and very sparse.

At some point, every element will be undefined, but the length won't be 0 — so it is empty, but it doesn't express that. How can I check if this has happened?

The best that I can think of is to loop through the whole monster and check if they're all undefined. But that would be too inefficient for my application.

役に立ちましたか?

解決

Two solutions I can think of. Both require some modification to your interactions with the array.

First solution

Keep a counter.

If you simply keep a counter that represents how many elements in the array are actually there, then the emptiness check is a mere comparison.

var n = 0;

// Adding something to the array:
myArr[2] = somethingDefined;
n ++;

// Removing from the array:
delete myArr[2];
n --;

// Check if empty
if(n == 0) {
   console.log("myArr is empty.");
}

Second solution

Use splice instead of delete

splice will actually modify the array instead of setting the values to undefined. Example:

myArr.splice(2, 1); // Get rid of myArr[2]

And this mutates the array and will change .length so you can easily check the actual length of the array. Note that splice is less efficient (and given you seem to care about the efficiency, the first solution is probably more applicable).

他のヒント

You can use the array method some that quits when it hits any non falsy value:

a.some(Boolean); // returns false if the array has no truthy values

or, if false is a possible value, check for not === undefined:

a.some(function(itm){
   return itm !==undefined;
});

Though this may not be the most efficient, it does the trick quite succinctly:

Object.keys(myArr).length === 0

It might be appropriate for less performance-intensive applications.

You can simulate the removal of your list by using a call to splice:

myArr.splice(indexToRemoveAt,nubmerOfElementsToRemove);

So for your use case:

myArr.splice(indexToRemoveAt,1)

Worked for me sparseArray.size()==0

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top