FVGCC - JavaScript Part 3



Arrays and Lists in Computer ScienceData Structure: in Computer Science the term “Data Structure” refers to a specific way of organizing and referencing data. There are entire college courses devoted to Data StructuresArray: an array is a Data Structure that uses a single variable to store and access multiple values; an individual value (element) is accessed by an IndexEach numbered value is called an Element of the arrayIndex is sometimes called a subscriptThe index of the first element in the array is either 0 or 1 depending on the languageArrays in some programming languages can be more complex than a simple list but that is outside the scope of our discussionLists in ScratchSample Program https:/scratch.mit.edu/projects/95235421/ Created by Robin to demonstrate the use of lists and Index in ScratchIndex: Lists in Scratch start with the Index 1Create a List: on the Scripts tab, select the Data category and click Make A List. Clicking OK adds blocks to the Data category if this is the first list in the projectAdd an item to the end of the List: Add an item at a specific Index: Remove an item from the list by giving this block the Index of the item to remove Retrieve a value at a specific Index: Get the number of items in the List: Determine whether the List contains a specific value: Check the checkbox in front of the List name on the data tab to display it. In our example, we have added 10 elements to the Acronyms list: Note that the first item is at Index 1 and that length: 10 is displayed under the listParallel Arrays/Lists:The Personal Acronym Assistant project demonstrates the use of Parallel Lists to use a value from one list to look up a related value in a second list. This is a great algorithm to know as it is widely used in programming! In this project we have the Acronyms list as shown above and a second list named Meanings that is not display. The Meanings list contains the explanations for the acronyms and they are in the same order as in the Acronyms list. So at Index 1 in Acronyms we have “AFK” and at Index 1 in Meanings we have “Away From Keyboard”. The basic algorithm is:Look up specified value in Acronyms List to get the IndexIf not found, take appropriate action such as notifying the userIf found, get the value from the Meanings List using the same Index, and take appropriate action such as displaying it to the userArrays in JavaScriptIndex: in JavaScript the Index is 0-basedCreate an Array by Declaring the Variable:Declare a variable using square brackets; empty brackets for an empty array; or enter a comma-separated list of values to add them to the array:var acronyms = [ ]; //declares an empty array; the length is 0;var acronyms = [“BRB”, “TYVM”, “LOL”); //creates an array containing 3 elements; length is 3 Display the values in the Array:In document.write() or console.log, pass the array’s name in as the value in parentheses (i.e., the function argument) . The output will be a comma-separated list of all of the valuesdocument.write (acronyms);Get the value of a specific item in the listUse the index, placing it in square brackets after the name of the array:var myFavoriteAcronym = acronyms[2];In the example myFavoriteAcronym will contain “LOL”; remember that the first item is at 0, so the 3rd item is at index 2Get the number of items in the list - Use the length property:var numberOfAcronyms = acronyms.length; Add an item at a specific Index of the Array: acronyms[2] = “ROFL”;Warning: this statement REPLACES whatever was at that Index! Add an item to the end of the Array:If we know the index of the last item in the array, we could add the new item using the next higher index. Let’s say there are 3 elements in the array, numbered; their indices are 0, 1, 2. We could “hard-code” in the index of 3 for the next one:acronyms[3] = “IMHO”;But a better practice to be sure we get it at the end and are not overwriting another item, we can use the length to get the index. Acronyms[acronyms.length] = “IMHO”;Determine whether the List contains a specific valueUse the IndexOf method: we’ve talked about procedures and functions in previous discussions. A Method is actually the same as a function except it belongs to a particular type of structure or object, in this case, the IndexOf method belongs to the Array structure. It looks for the value passed in as an argument (remember arguments and parameters?) and if it finds a match it returns the Index of the matching element. If it does not find a match it returns the value -1In this example, we prompt the user to enter an acronym and we store the answer in a variable named “answer:var answer = prompt("Enter an acronym..");We then look for the user’s answer in our array of acronyms:var match = acronyms.indexOf(answer);If the user’s answer is found the variable match will contain its Index; if it is not found match will contain -1Let’s try using the Parallel Arrays Algorithm in JavaScript!In Chrome, open the Console (F12) and get a clean page by typing About:blank in the address barSelect the Console tabDeclare and populate the two Parallel Arrays: Use whatever acronyms and meanings you like, just be sure to match the order between the 2: var acronyms = ["AFIK", "AFK", "TTFN", "NP", "LOL"];var meanings = ["As far as I know", "Away from keyboard", "TaTa for now", "No problem", "Laughing out loud"];Take a look at the values of each array; by either of these methods (or both if you want to practice):For loop:for (i = 0; i < acronyms.length; i++){console.log(acronyms[i]);};Or simply output the array:Console.log(acroynms);Display the list of Acronyms on the Web page:Document.write(acroynms);Ask the user for an acronym and store it in a variable:var answer = prompt("Enter an acronym..");Look up the user’s answer in the array of acronyms. Because JavaScript is case-sensitive, let’s add a user-friendly feature to convert the input to upper case. var match = acronyms.indexOf(answer.toUpperCase());Take a look at the results of the look up:console.log(match); //if this value is -1 a match was not found!If a match was found get the element from the meanings Array having the same index; otherwise display a message:if (match >= 0){alert("I found it! The meaning is: " + meanings[match]);}else{alert("Sorry, I could not find " + answer);}JSFiddle and Makey Makey!We will start with a very simple project in the JSFiddle environment and add JavaScript to check the input from a key and resize an image based on which key is pressedJSFiddle: “Sandbox” environment for developers to play in to compose Web pages Screen has separate section for each of the 3 main types of code that make up a Web page: HTML, CSS, and JavaScriptHTML Pane: In JsFiddle, the HTML area is for entering the contents of the Body of the HTML page.We are going to start with a large heading by entering text between <h1></h1> tags<h1>Let's try Makey Makey!</h1>Add an image: <img id="myIcon" src="" alt="Lop-eared Holland Rabbit" height="100">Include an id for the image; this is crucial for accessing the image in JavaScript code; in this example we include id=”myIcon” The src attribute requires the full path to an image; an excellent source for finding images is height attribute height=”100” is the starting height for the image; it is also the attribute that we will manipulate using JavaScriptYour HTML should look something like this:JavaScript Pane: we are going to define a function and assign it to execute each time a key is pressed down. If it is one of the arrow keys the size of the image will change.Define a function: use the keyword “function” followed by a name you want for the function, followed by a parameter list in parentheses, followed by the code block enclosed in bracketsfunction evaluateKey(event){ code goes here….}Inside the function code block put code to:Get your image element from the HTML document and store a reference to it in a variable. In JavaScript the getElementById function does this; it is why we had to use an id attribute when we wrote the img element in the document. var icon = document.getElementById("myIcon");Log the value of the input to the console. We are using this just for learning and debugging purposes. In JavaScript, event.which contains a number that indicates which key was pressedconsole.log(event.which);Use conditional logic to take action based on the value of the key pressed. For a list of codes corresponding to keys see the evaluateKey function with the key down event:document.onkeydown=evaluateKey;The full JavaScript code should look like this:function evaluateKey(event){ var icon = document.getElementById("myIcon"); console.log(event.which); if (event.which == 38) { console.log("up"); myIcon.height += 10; } else if (event.which ==39) { console.log("right"); myIcon.width += 10; } else if (event.which ==40) { console.log("down"); myIcon.height -= 10; } else if (event.which == 37) { console.log("left"); myIcon.width -= 10; }; }; document.onkeydown=evaluateKey; //tie the above function to key downHook up your Makey Makey and make the picture change sizes!Look up some other key codes and add code to do something using your JavaScript skills!If you have time for a more advanced way to do conditionals when there are many choices, take a look at the switch statement: Exam Challenge:From the AP Computer Science Principles Exam, this is sample question #22: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download