1 / 23

CNIT 133

CNIT 133 . Objects and Arrays. Objectives. JavaScript – Objects and Arrays Creating Objects Object Properties Object as Associative Arrays Universal Object Properties and Methods Arrays Reading and Writing Array Elements Array Methods. Object and Arrays.

MartaAdara
Download Presentation

CNIT 133

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CNIT 133 Objects and Arrays

  2. Objectives • JavaScript – Objects and Arrays • Creating Objects • Object Properties • Object as Associative Arrays • Universal Object Properties and Methods • Arrays • Reading and Writing Array Elements • Array Methods

  3. Object and Arrays • Objects and arrays are two fundamental datatypes in JavaScript. • They are collections of values. • An object is a collection of named values • An array is a specialized kind of object that behaves as an ordered collection of numbered values

  4. Creating Objects • An object is an unordered collection of properties, each of which has a name and a value. • The named values may be primitive values (number or string or boolean), or may be another objects. • The easiest way to create an object is to include an object literal in your JavaScript code. • An object literal is a comma-separated list of property name/value pairs, enclosed within curly braces: var empty = { }; // an object with no properties var point = { x:0, y:0 }; var circle = { x:point.x, y:point.y+1, radius:2 }; var homer = { “name”:”homer simpson”, “age”: 34, “married”: true, “occupation”: “plant operator”, “email”: homer@example.com }; • The new operator can create specialized kinds of objects: var a = new Array(); // create an empty array var d = new Date(); // create an object with current date & time • It is also possible to define your own constructor functions.

  5. Object Properties • You normally use the . to access the value of an object’s properties • The value on the left of the . should be the object whose property you want to access (the name of the variable that contains the object reference or expression that evaluates to an object) • The value on the right of the . should be the name of the property (must be an identifier, not a string or an expression) • You can create a new property of an object simply by assigning a value to it: var book = {}; // create a new object with empty object literal book.title = “JavaScript: the definitive Guide”; book.chapter1 = new Object(); book.chapter1.title = “Introduction to JavaScript”; book.chapter1.pages = 11; book.chapter2 = { title: “Lexical Structure”, pages: 6}; alert(“Outline: “ + book.title + “\n\t” + “Chapter 1 “ + book.chapter1.title + “\n\t” + “Chapter 2 “ + book.chapter2.title);

  6. Enumerating Properties • The for/in loop provides a way to loop through, or enumerate, the properties of an object • This can be useful when working with objects that may have arbitrary properties whose names you do not know in advance: function displaypropnames(obj) { var names = “”; for(var nm in obj) names += nm + “\n”; alert(names); } • NOTE: the for/in loop does not enumerate properties in any specific order, and it does not enumerate certain predefined properties or methods

  7. Checking Property Existence • The in operator can be used to test for the existence of a property. • The left side of this operator should be the name of the property as a string. • The right side should be the object to be tested: // if o has a property named “x”, then set it if (“x” in o) o.x = 1;

  8. Deleting Properties • You can use the delete operator to delete a property of an object: delete book.chapter2; • Note that deleting a property does not merely set the property to undefined; it actually removes the property from the object. • After deletion, for/in will not enumerate the property • And the in operator will not detect it.

  9. Objects as Associative Arrays • The . operator is used to access the properties of an object. • It is possible to use the [ ] operator, which is more commonly used with arrays, to access these properties. • The following two JavaScritp expression have the same value: object.property object[“property”] • The first statement’s property name is an identifier • The second statement’s property name is a string • When you use the . operator to access a property of an object, the name of the property is expressed as an identifier. Identifiers must be typed literally; they are not a datatype, so they cannot be manipulated by the program. • When you access a property of an object with the [ ] array notation, the name of the property is expressed as a string. Strings are JavaScript datatypes, so they can be manipulated and created while a program is running: var addr = “”; for (i = 0; i < 4; i++) { addr += customer[“address” + i] + “\n”; } • This code reads and concatenates the address0, address1, … properties of the customer object. • When an object is used in this fashion, it is often called an associative array – a data structure that allows you to dynamically associate arbitrary values with arbitrary strings. The term “map” is often used to describe this situation as well: JavaScript objects map strings (property names) to values.

  10. Universal Object Properties and Methods • All objects in JavaScript inherit from the Object class. • All objects also support the properties and methods defined by Object.

  11. The Constructor Property • In JavaScript, every object has a constructor property that refers to the constructor function that initializes the object. var d = new Date(); d.constructor == Date; // evaluates to true • The constructor property can help determine the type of an object: if ((typeof o == “object”) && (o.constructor == Date)) // then do something with the Date object • The instanceof operator checks the value of the constructor property, so the code could be written: if ((typeof o == “object”) && (o instanceof Date)) // then do something with the Date object

  12. The toString( ) Method • The toString( ) method takes no arguments; it returns a string that somehow represents the value of the object on which it is invoked. • JavaScript invokes this method of an object whenever it needs to convert the object to a string (e.g. use in + operator, alert() method) • When an array is converted to a string, you obtain a list of the array elements, each converted to a string. • When a function is converted to a string, you obtain the source code for the function.

  13. The valueOf( ) Method • The valueOf( ) method is called when JavaScript needs to convert an object to some primitive type other than a string – typically, a number. • JavaScript calls this method automatically if an object is used in a context where a primitive value is required.

  14. 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”.

  15. Arrays • 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

  16. 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.

  17. 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 10000.

  18. 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()).

  19. Array Length • 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

  20. 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]);

  21. 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.

  22. 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 the 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

  23. 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()

More Related