When using the delete operator with an array value, the array’s length property is not affected, but the element at the specified index is removed and leaves an empty slot in the array.
This creates a sparse array, which can lead to unexpected behavior when iterating or checking array properties.
The recommended way to remove an element from an array is by using the Array#splice() method, which properly updates the array’s length and shifts remaining elements.
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
@param ― start The zero-based location in the array from which to start removing elements.
@param ― deleteCount The number of elements to remove. Omitting this argument will remove all elements from the start
paramater location to end of the array. If value of this argument is either a negative number, zero, undefined, or a type
that cannot be converted to an integer, the function will evaluate the argument as zero and not remove any elements.
@returns ― An array containing the elements that were deleted.
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
@param ― start The zero-based location in the array from which to start removing elements.
@param ― deleteCount The number of elements to remove. Omitting this argument will remove all elements from the start
paramater location to end of the array. If value of this argument is either a negative number, zero, undefined, or a type
that cannot be converted to an integer, the function will evaluate the argument as zero and not remove any elements.
@returns ― An array containing the elements that were deleted.
splice(1, 1);
declare const
const obj: {
[key:string]:number;
}
obj: { [
key: string
key:string]:number };
delete
const obj: {
[key:string]:number;
}
obj["key"];
declare const
const map:Map<string, number>
map:
interface Map<K, V>
Map<string, number>;
const map:Map<string, number>
map.
Map<string, number>.delete(key: string): boolean
@returns ― true if an element in the Map existed and has been removed, or false if the element does not exist.
If you intentionally want to create sparse arrays with empty slots, you can disable this rule.
Some codebases may use sparse arrays for specific algorithms or memory optimization purposes.