Advertisement
pdrenovska

Javascript - Using Objects Task 2

Mar 28th, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <title>JS Functions Task 1</title>
  5.         <link href="css/js-console.css" rel="stylesheet" type="text/css" />
  6.     </head>
  7.     <body>
  8.         <p>Write a function that removes all elements with a given value
  9.             <br/>var arr = [1,2,1,4,1,3,4,1,111,3,2,1,"1"];
  10.             <br/>arr.remove(1); //arr = [2,4,3,4,111,3,2,"1"];
  11.             <br/>Attach it to the array class. Read about prototype and how to attach methods
  12.         </p>
  13.         <div id="js-console"></div>
  14.         <script src="js/js-console.js"></script>
  15.         <script>
  16.             //Add dynamically to the already defined object a new function
  17.             Array.prototype.remove = function (number) {
  18.                 for (var i = 0; i < this.length; i++) {
  19.                     if (this[i] === number)
  20.                         this.splice(i, 1); // Here we don't use delete, because delete will not update the length of the array
  21.                                            // neither really erases the element, only replaces it with the special value undefined
  22.                 }
  23.             };
  24.             var arr = [1, 2, 1, 4, 1, 3,"1", 4, 1, 111, 3, 2, 1, "1"];
  25.             jsConsole.writeLine("We're given this array: ");
  26.             jsConsole.writeLine(arr.join(', '));
  27.  
  28.             arr.remove(1);
  29.             jsConsole.writeLine("After remove the digit 1: ");
  30.             jsConsole.writeLine(arr.join(', '));
  31.  
  32.             arr.remove("1");
  33.             jsConsole.writeLine("After remove the string 1: ");
  34.             jsConsole.writeLine(arr.join(', '));
  35.         </script>                        
  36.     </body>
  37. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement