InterviewSolution
| 1. |
JavaScript has dynamic types. How? |
|
Answer» Remove a Single Element To remove a single element from an array in JavaScript, the splice() method is used. With that you can also replace, and/or add elements in an array. Let’s say we have the following array: var myArr = ["Java", "PHP", "HTML", "jQuery", "ECLIPSE", "NetBeans"];We are USING the splice() method to remove a single element by setting the location from where it start, and the number of elements to be removed. Here, we have set 1, therefore only a single element will get removed: myArr.splice(3, 1);The following is an EXAMPLE: <html> <head> <title>JavaScript Splice Method</title> </head> <body> <script> var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"]; document.write("<br />Array before removing an element = " + myArr ); rem = myArr.splice(3, 1); document.write("<br />Removed element = " + rem); document.write("<br />Array after removing an element = " + myArr ); </script> </body> </html>The output: Array before removing an element = Java,PHP,HTML,jQuery,Eclipse,NetBeans Removed element = jQuery Array after removing an element = Java,PHP,HTML,Eclipse,NetBeansRemove more than one element To remove more than one element and in a range, use the splice() method. Let’s say we have the following array: var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed: We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed: myArr.splice(2, 3);In the following example, we are deleting 3 elements starting from the 3rd position: <html> <head> <title>JavaScript Splice Method</title> </head> <body> <script> var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"]; document.write("<br />Array before removing 3 elements = " + myArr ); // removing multiple elements rem = myArr.splice(2, 3); document.write("<br />Array after removing 3 elements = " + myArr ); </script> </body> </html>The output displays the array after removing 3 elements: Array before removing 3 elements = Java,PHP,HTML,jQuery,Eclipse,NetBeans Array after removing 3 elements = Java,PHP,NetBeans |
|