Tuesday, August 21, 2018

Add and remove elements form array in javascript

Note:I have coded using typescript but javascript functions remains same

Declaration of Array:




numberoftasks: string[];


Adding elemnts in Array using push function



addtask() {
console.log('Adding Task: ' + this.form.value.task);
this.numberoftasks.push(this.form.value.task);
console.log(this.numberoftasks);
}


Output:["user1", "admin", "kavitha"]


Splice function with deletecount and start index 


deletetask(index) {
console.log('Deleting' + index);
this.numberoftasks.splice(index,1);
this.form.controls['task'].reset();
}

I am passing index as 0  in deletetask function and below is output.






Splice function Without deletecount


deletetask(index) {
console.log('Deleting' + index);
this.numberoftasks.splice(index);
this.form.controls['task'].reset();
}



If you wont pass any delete count then it will consider index as start index of elements needs to be deleted and it will delete all elements coming after this index.

e.g. if  index is 0  deletetask(0)

then it will delete entire array.


e.g. if  index is 1  deletetask(1)

then it will delete Elmets coming after index 1.

so out put will be like
["user1"]




No comments:

Post a Comment

How to check whether operating system is 64 bit or 32bit?

What is 32 and 64 bit operating system? The terms 32-bit and 64-bit refer to the way a computer's processor that is CPU, handles info...