Friday, May 31, 2013

.pop() in JavaScript will throw away the last item on an array, as if almost the opposite of .push()

In keeping with my silly supreme court example, if a file named defineyesmen.js merely contained:

var yesmen = ['Alito', 'Kagan', 'Kennedy', 'Roberts', 'Scalia', 'Thomas'];

 
 

...then the dropdown list given in the HTML below would end up with the contents of the array minus Clarence Thomas.

<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1,maximum-
            scale=1,minimum-scale=1,user-scalable=no"/>
      <meta name="apple-mobile-web-app-capable" content="yes" />
      <title>Whatever</title>
      <link rel="stylesheet" type="text/css" href="styles.css" media="screen">
      <style type="text/css" media="all">
         #list {
            width: 220px;
         }
      </style>
   </head>
   <body style="overflow-y:hidden; overflow-x:hidden;">
      <select id="list">
         <option selected>change me to something else</option>
      </select>
      <script src="defineyesmen.js" type="text/javascript"></script>
      <script type="text/javascript">
         yesmen.pop();
         for (var i=0; i<yesmen.length; i++)
         {
            var opt = document.createElement("option");
            opt.text = yesmen[i];
            opt.value = yesmen[i];
            document.getElementById("list").options.add(opt);
         }
      </script>
   </body>
</html>

 
 

If an array is empty it will just stay empty upon a .pop() which seems to cause no error.

No comments:

Post a Comment