CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Intro to Javascript CS Client Side Scripting CS380 2.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Arrays.
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Case, Arrays, and Structures. Summary Slide  Case Structure –Select Case - Numeric Value Example 1 –Select Case - String Value Example  Arrays –Declaring.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 8 Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
C++ for Engineers and Scientists Third Edition
JavaScript, Third Edition
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
CSE 341 Lecture 24 JavaScript arrays and objects slides created by Marty Stepp
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Expression.
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Built-in Data Structures in Python An Introduction.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
Unit 12 JavaScript Arrays Instructor: Brent Presley.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Working with Loops, Conditional Statements, and Arrays.
Chapter 14 JavaScript: Part II The Web Warrior Guide to Web Design Technologies.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and Conditional Statements Creating a Monthly Calendar.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming javascript arrays.
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
JavaScript and Ajax (JavaScript Arrays) Week 5 Web site:
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
Chapter 11 - JavaScript: Arrays
Chapter 6 JavaScript: Introduction to Scripting
Containers and Lists CIS 40 – Introduction to Programming in Python
SEEM4570 Tutorial 05: JavaScript as OOP
JavaScript: Functions.
JavaScript and Ajax (Expression and Operators)
Objectives Create an array Work with array properties and methods
ARRAYS MIT-AITI Copyright 2001.
String and Lists Dr. José M. Reyes Álamo.
JavaScript CS 4640 Programming Languages for Web Applications
Arrays.
JavaScript CS 4640 Programming Languages for Web Applications
Introduction to Computer Science
Presentation transcript:

CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Agenda My Web Site: (download syllabus, class notes). Arrays. Array Elements (reading, writing, adding, deleting). Array length property. for Loop and Arrays. Associative Arrays. Multidimensional Arrays. Arrays Methods.

Arrays An array is an ordered collection of values Each value is called an element, and each element has a numeric position in the array, known as its index JavaScript is an untyped language, an element of an array may be of any type, and different elements of the same array may be of different types. Array elements may even contain other arrays, which allows you to create data structures that are arrays of arrays. An array is also an object. A typeof operator applied to an array value, it returns the string “object”. Arrays are particularly useful for storing data that are somehow related to each other, such as student names, phone numbers, etc. JS always begins numbering array elements at zero

Arrays (continue…) There are three ways to declare an array.  With new operator var cups = new Array(); var cups = new Array(8); // 8 elements  NOTE : expected size only, can only put size at declare time, allow to add elements to this array dynamically.  With dense array, declare and initialize at the same time var days = new Array("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"); var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");  With array literal (easy way) var weekendDays = ["Friday", "Saturday", "Sunday"]; Note: var cups = new Array(); and var cups = []; are the same with empty array. NOTE: cups = new Array(1, 2,, 4); // for loop cannot display all data. NOTE: cups = [1,2,, 4]; // for loop is ok to display all data.

Arrays (continue…) The easiest way to create an array is with an array literal, which is simply a comma-separated list of array elements within square brackets: var empty = [ ]; var primes = [2, 3, 5, 7, 11]; var misc = [1.1, true, "a"]; The values in an array literal need not be constants; they may be arbitrary expressions: var base = 1024; var table = [base, base + 1, base + 2, base +3]; Another way to create an array is with the Array( ) constructor in three distinct ways: Call it with no arguments: var a = new Array( );// creates an empty array var a = [ ];// same as above Explicitly specify values for the first n elements of an array: var a = new Array (5, 4, 3, 2, 1, "testing"); Call it with a single numeric argument, which specifies a length: var a = new Array(10);// creates an array with 10 elements

Reading and Writing Array Elements You access an element of an array using the [ ] operator You can use this syntax to both read and write the value of an element of an array: value = a[0]; a[1] = 3.14; i = 2; a[i] = 3; a[i + 1] = "hello"; a[a[i]] = a[0]; In JavaScript, the first element of an array is at index 0.

Adding New Elements to an Array In JavaScript, an array can have any number of elements, and you can change the number of elements at any time. To add a new element to an array, simply assign a value to it: a[10] = 10; Arrays in JavaScript may be sparse. Array indexes need not fall into a contiguous range of numbers; a JavaScript implementation may allocate memory only for those array elements that are actually stored in the array: a[0] = 1; a[10000] = "this is element 10,000"; // JavaScript allocates memory only for array indexes 0 and

Deleting Array Elements The delete operator sets an array element to the undefined value, but the element itself continues to exist. To actually delete an element, so that all elements above it are shifted down to lower indexes, you must use an array method (Array.shift(), Array.pop(), and Array.splice()).

Array length property All arrays, whether created with the Array() constructor or defined with an array literal, have a special length property that specifies how many elements the array contains. More precisely, since arrays can have undefined elements, the length property is always one larger than the largest element number in the array. The length property is automatically updated. var a = new Array();//a.length == 0, no elements defined a = new Array(10);//a.length == 10, empty elements 0-9 defined a = new Array(1,2,3);//a.length == 3, elements 0-2 defined a = [4,5];//a.length == 2, element 0 & 1 defined a[5] = -1;//a.length == 6, elements 0,1 and 5 defined a[49] = 0;//a.length == 50, elements 0,1,5, and 49 defined

Iterating Through Arrays The most common use of the length property of an array is to allow you to loop through the elements of an array: var fruits = ["mango", "banana", "cherry", "pear"]; for (var i = 0; i < fruits.length; i++) { alert(fruits[i]); } This example assumes, elements of the array are contiguous and begin at element 0. If this is not the case, you should test that each array element is defined before using it: for (var i = 0; i < fruits.length; i++) { if (fruits[i]) { alert(fruits[i]); }

for Loop and Arrays Array var cups = new Array("Lemonade", "iced tea", "Pepsi"); Array var i; for (i = 0; i < cups.length; i++) { document.write(i, ". ", cups[i], " "); }

Using Placeholders in an array literal Uninitialized element’s value is undefined. We declared the second array element by using a comma placeholder in our array literal (see next page sample). Since we did not provide an initializing value, its value is undefined. (similar to declaring a variable without initializing it). NOTE: all browsers seem to handle comma placeholders in the middle of an array literal the same. However, Netscape, IE, and Opera handle extra comma listed at the end of an array differently. Netscape create empty elements for each comma at the end of the array, but does not assume an additional element after the last comma IE and Opera create empty elements for each comma, plus one to follow the last comma.

Using Placeholders in an array literal sample Array placeholder var cups = ["Lemonade",, "Pepsi"]; Array placeholder var i; for (i = 0; i < cups.length; i++) { document.write(i, ". ", cups[i], " "); }

Empty elements at the end of an array literal Array empty element at end var cups = ["Lemonade", "Ice tea", "Pepsi",,, ]; Array placeholder at the end var i; for (i = 0; i < cups.length; i++) { document.write(i, ". ", cups[i], " "); }

Empty elements at the end of an array literal result Result of Netscape 0. Lemonade 1. Ice tea 2. Pepsi 3. undefined 4. undefined Result of IE and Opera 0. Lemonade 1. Ice tea 2. Pepsi 3. undefined 4. undefined 5. undefined

Truncating and Enlarging Arrays The length property of an array is a read/write value. If you set length to a value smaller than its current value, the array is truncated to the new length; any elements that no longer fit are discarded, and their values are lost. If you make length larger than its current value, new, undefined elements are added at the end of the array to increase it to the newly specified size.

Associative Arrays Array elements can also be indexed by their names, if a name has been defined. An array indexed by a word, rather than by an ordinal number, is called associative array. Support for associate arrays is a nice feature of JavaScript.

Associative Arrays sample document.images[0] // same as document.images["products"] document.images[1] // same as document.images["services"] document.images[2] // same as document.images["contact"] document.images[3] // same as document.images["home"]

Associative Arrays sample (continue…) var birthdays = new Array(); birthdays["Tim"] = "May 15"; Birthdays["Mom"] = "Mar 22"; birthdays["Jean"] = "Feb 18"; birthdays["Paul"] = "Jan 25"; document.write("Tim\’s birthday is ", birthdays["Tim"], " ");

Dynamic Array length in JS var colors = ["white", "blue", "red"]; document.write("colors length: ", colors.length, " "); // 3 colors[7] = "pink"; document.write("colors length: ", colors.length, " "); // 8

Dynamic Array length in JS sample Array dynamic length var colors = ["white", "blue", "red"]; Dynamic Array length var i; document.write("colors length: ", colors.length, " "); document.write("colors contents: "); for (i = 0; i < colors.length; i++) { document.write(i, ". ", colors[i], " "); } colors[7] = "pink"; document.write("colors length: ", colors.length, " "); document.write("colors contents: "); for (i = 0; i < colors.length; i++) { document.write(i, ". ", colors[i], " "); }

Dynamic Array length in JS result colors length: 3 colors contents: 0. white 1. blue 2. red colors length: 8 colors contents: 0. white 1. blue 2. red 3. undefined 4. undefined 5. undefined 6. undefined 7. pink

Multidimensional Arrays JavaScript does not support true multidimensional arrays, but it does allow you to approximate them quite nicely with arrays of arrays. To access a data element in an array of arrays, simply use the [ ] operator twice. Create a multidimensional array: var table = new Array(10);// 10 rows of the table for (var i = 0; i < table.length; i++) { table[i] = new Array(10);// each row has 10 columns } Initialize a multidimensional array: for (var row = 0; row < table.length; row++) { for (var col = 0; col < table[row].length; col++) { table[row][col] = row * col; } Use the multidimensional array to compute 5 * 7 var product = table[5][7]; // 35

Array Methods In addition to the [ ] operator, arrays can be manipulated through various methods provided by the Array class. join() reverse() sort() concat() slice() splice() push() and pop() unshift() and shift() toString() and toLocaleString()

Array Method – toString() arrayName.toString(), this method joins the elements of an array together and returns the resulting string. Every object in JS has a toString() method. An object’s toString() method is automatically called whenever you try to represent the object as text or concatenate it to text. NOTE: use the toString() method to quickly show the contents of the array.

Array Method – toString() sample Array toString Array method – toString() var cups = ["Lemonade", "Ice Tea", "Pepsi"]; document.write("Using cups: ", cups, " "); document.write("Using cups.toString(): ", cups.toString(), " "); var myCups = cups.toString(); document.write("Using myCups or myCups.toString(): ", myCups.toString(), " ");

Array Method – concat() arrayName.concat(arrayToadd1[, arrayToadd2, arrayToadd3,…]) Combine two or more arrays together into one, i.e., to concatenate one or more arrays on to the end of another array. It does not change the content of the original arrays. var oldFriends = ["David", "Jane", "Paul"]; var newFriends = ["April", "Peter"]; var partyInvites = oldFriends.concat(newFriends); // partyInvites is an array with data from oldFriends and newFriends, use for/loop to get the data partyInvites = oldFriends + newFriends; // partyInvites is a string with strings from oldFriends + newFriends, cannot use for/loop to get the data

Array Method – concat() sample Array concat Array method – concat() var i; var oldFriends = ["David", "Jane", "Paul"]; var newFriends = ["April", "Peter"]; var partyInvites = oldFriends.concat(newFriends); document.write("oldFriends toString: ", oldFriends, " "); document.write("newFriends toString: ", newFriends, " "); document.write("partyInvites toString: ", partyInvites, " "); document.write("partyInvites for/loop: ", " "); for (i = 0; i < partyInvites.length; i++) { document.write(i, ". ", partyInvites[i], " "); } var str_partyInvites = oldFriends + newFriends; document.write("str_partyInvites toString: ", str_partyInvites, " "); document.write("str_partyInvites for/loop: ", " "); for (i = 0; i < str_partyInvites.length; i++) { document.write(i, ". ", str_partyInvites[i], " "); } document.write("str_partyInvites has 26 undefined, the size of the string");

Array Method – join() arrayName.join([separator]) The join method is similar to the toString() method. The main difference is that the join method allows you to optionally specify the delimiter or separator you want to appear between elements. If no separator is specified, the array elements are separated by a comma. One common use of the join method is to create a string of an array’s contents by assigning the result of the join operation to a variable.

Array Method – join() sample Array join Array method – join() var oldFriends = ["David", "Jane", "Paul"]; document.write("oldFriends.join(\" \"): ", oldFriends.join(" "), " "); document.write("oldFriends.join(\" and \"): ", oldFriends.join(" and "), " "); document.write("oldFriends.join(): ", oldFriends.join(), " "); document.write("Program end");

Array Method – reverse() arrayName.reverse() This method reverses the order of the elements in an array. NOTE: BE CAREFUL, it actually modifies the array itself.

Array Method – reverse() sample Array reverse Array method – reverse() var oldFriends = ["David", "Jane", "Paul"]; document.write("oldFriends originally: ", oldFriends, " "); oldFriends.reverse(); document.write("oldFriends.reverse(): ", oldFriends, " "); document.write("Program end");

Array Method – sort() arrayName.sort([compareFunction]) By default, this method sorts the elements of an array alphabetically (Lexicographically) if no compare function is specified. (compare as strings). Note: this method permanently changes the order of the array. To sort in alphabetically and in descending order: myArray.sort(); myArray.reverse();

Array Method – sort() (continue…) To sort in numerical order, you need to provide a user-defined compare function. To sort in numerical ascending order: arrayName.sort(compareFun1); function compareFun1(a, b) { return a - b; } To sort in numerical descending order: arrayName.sort(compareFun2); function compareFun2(a, b) { return b - a; }

Array Method – sort() sample Array sort Array method – sort() var mixArray = ["hi", "Hi", "HI", -1.5, 9, 700.5, 700, 1, -1]; var numArray = [9.75, -4, 1, 7.5, 3, 2, 9, -4.25, 11, 3, 8, 900]; var ascArray=[10,20,15,5]; var decArray=[10,20,15,5]; function compareFun1(a, b) { return a - b; } function compareFun2(a, b) { return b - a; } document.write("mixArray after sorted Alphabetically: ", mixArray.sort(), " "); document.write("numArray after sorted Alphabetically: ", numArray.sort(), " "); document.write("ascArray after sorted Numerically: ", ascArray.sort(compareFun1), " "); document.write("decArray after sorted Numerically: ", decArray.sort(compareFun2), " "); document.write("numArray after sorted Numerically: ", numArray.sort(compareFun1), " ");

Array Method – sort() sample result mixArray after sorted Alphabetically: -1,-1.5,1,700,700.5,9,HI,Hi,hi numArray after sorted Alphabetically: -4,-4.25,1,11,2,3,3,7.5,8,9,9.75,900 ascArray after sorted Numerically: 5,10,15,20 decArray after sorted Numerically: 20,15,10,5 numArray after sorted Numerically: -4.25,-4,1,2,3,3,7.5,8,9,9.75,11,900

Array Method – slice() arrayName.slice(beginIndex[, endIndex]) It returns an extracted segment of an array as a new array. It does not modify the original array. slice() begins at the beginIndex and extracts up to, but not including, the end index. If no endIndex is specified, slice() extracts the element from the beginIndex to the end of the array. If the endIndex specified is negative, it indicates the offset from the end of the array.

Array Method – slice() sample Array slice Array method – slice() var zList = ["item0", "item1", "item2", "item3", "item4", "item5", "item6", "item7"]; var ary_24 = zList.slice(2,4); var ary_2Offset2 = zList.slice(2,-2); var ary_2Toend = zList.slice(2); document.write("New array of slice(2,4): ", ary_24, " "); document.write("New array of slice(2,-2): ", ary_2Offset2, " "); document.write("New array of slice(2): ", ary_2Toend, " "); document.write("Program end");

A Summary of Array Methods MethodDescription concat(ary2[,ary3,…])Concatenates two or more arrays and returns the result as a new array. join([separator])Returns all of the elements of an array joined together in a single string delimited by an optional separator, if no separator is specified, a comma is inserted between elements. pop()Removes and returns the last element of an array. push(ele1[,ele2,…])Appends one or more elements on to the end of an array and returns the array’s new length. reverse()Reverses the order of an array. This method actually modifies the array.

A Summary of Array Methods (continue…) MethodDescription shift()Removes and returns the first element of an array. slice(beginIndex[, endIndex])Returns an extracted segment of an array as a new array. sort([comparefunct])Sorts the elements of an array. This method actually modifies the array. splice(startIndex, howMany [,ele1, …])Modifies the contents of an array by adding and/or removing elements. It returns the items removed. This method is quite powerful. toString()Returns the array converted to a string; elements are delimited by a comma. unshift([ele1, ele2,…])Inserts one or more elements at the front of the array and returns the new length. NOTE: IE 5.5 does not return the new length

Using Numeric Arrays Creating a Numeric Array (1) var scores = new Array(4); scores[0] = 39; scores[1] = 40; scores[2] = 100; cores[3] = 49; Creating a Numeric Array (2) var scores = new Array(39, 40, 100, 49); Creating a Numeric Array (3) var scores = [39, 40, 100, 49];

Understanding Array length var test = new Array(); test[0] = 21; test[5] = 22; test.length // max index = 5, length is 6

Using String Arrays Creating a String Array (1) var names = new Array(30); names[0] = "Sue Smith"; names[1] = "Paul Baker"; Creating a String Array (2) var names = new Array("Sue Smith", "Paul Baker"); Creating a String Array (3) var names = ["Sue Smith", "Paul Baker"];

Splitting a String JS includes a string method called split, which splits a string into its component parts. To use this method, specify the string to split and a character to divide the parts, var test = "Sue P. Smith"; var parts = test.split(" "); The split method splits the test string at each space, resulting in three strings. These are stored in a string array called parts. After the split statement, the elements of parts contain the following: parts[0] = "Sue"; parts[1] = "P."; parts[2] = "Smith";

Joining an Array JS also includes an array method, join, which performs the opposite function. This statement reassembles the parts array into a string. var fullname = parts.join(" "); The value in the parentheses specifies a character to separate the parts of the array. In this case, a space is used, resulting in the final string "Sue P. Smith". NOTE: if you do not specify a character commas are used.