i am new with JavaScript. Pls help.
I was playing with the method - console.log. here is what i did:
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
delete iceCreamFlavors[iceCreamFlavors.length-1];
console.log(iceCreamFlavors[length-1])
the console came back with
undefined
if I do:
console.log(iceCreamFlavors[5])
it has no problem to print
Mint Chip
but if I do:
console.log(iceCreamFlavors[-1])
it came back with
undefined
so my question is why can't console.log work with index numbers in the backward order? Maybe there is not much use in reality, but I am just curious.
CodePudding user response:
delete
keyword is used to delete Object
properties and not array elements, to remove an array element use Array.prototype.filter()
or Array.prototype.splice()
Splice will modify the original array while filter will return a new array which passes the condition specified in callback.
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
iceCreamFlavors.splice(5, 1);
console.log(iceCreamFlavors);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
const filter = iceCreamFlavors.filter(x => x != 'Mint Chip');
console.log(filter);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Note: you can access array elements using array[index]
, the index has a range from 0 to array.length - 1
. Arrays starts from 0 index, which means first element will have index 0 and second will have index 1 so on
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
iceCreamFlavors.splice(5, 1);
console.log(iceCreamFlavors.length); // array length
console.log(iceCreamFlavors[iceCreamFlavors.length - 1]); // last element
console.log(iceCreamFlavors[0]); // first element
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
delete vs splice in array
delete will not change the length or reindex the array, the given element is removed but it is appeared as undefined
splice will completely remove the element along with changing the length and reindex the elements