If I have a JS associative array which is from what I gather is really an object, and I wish to remove an element, using delete myArr[someId]
will set the element to undefined, whilst splice won't work at all... so what is the alternative for an associative array if I wish to delete an element (rather than setting it to undefined
)
2. The splice() method changes the original array and slice() method doesn't change the original array.
The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
splice alters the length of an array.
The terminology in js can be confusing at first, so lets straighten that out.
Yes, pretty much everything in js is an object. However, there are differences in the data types.
An array can be used like as associative array, but it's different than an object literal.
var x = []; //array var y = {}; //object literal
An array is like a list. The keys of an array can be a numerical index or a string.
var x = ['a','b']; // x[0] === 'a', x[1] === 'b'; var x = []; x['one'] = 'a'; x['blah'] = 'b';
Object literals are like dictionaries. They can be used in a similar way.
var x = { 0: 'a', 1: 'b' }; var x = { one: 'a', two: 'b' };
However, this is where you need to understand the differences.
You can use an array like an object literal, but you can't use an object literal quite like an array.
Arrays have the automated "length" property, that increments and decrements automatically based on the total number of elements in the array. You don't get this with object literals. Arrays also get all of the other array-specific methods like shift, unshift, splice, pop, push, etc. Object literals don't have those methods.
Let's talk about delete and what happens on an array and on an object literal.
var x = ['a', 'b']; //["a", "b"] delete x[0]; //[undefined, "b"] var x = {0:'1', 1:'b'}// { 0:"1", 1:"b"} delete x[0]; // { 1:"b" }
If you perform a delete on an element of an array, the length of the array doesn't change. The element index is preserved and the value is set to 'undefined';
Conversely, performing a delete on an object literal removes the key/value from the object.
Finally, if you want to remove an element from an array.
var x = ['a', 'b']; x.splice(0,1); //modifies x. ['b']
So, in summary use delete on object literals. Use splice on arrays.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With