CSE 341 Lecture 24 JavaScript arrays and objects slides created by Marty Stepp

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.
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Arrays Strings and regular expressions Basic PHP Syntax CS380 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.
Julian on JavaScript: Objects Julian M Bucknall, CTO.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
TCSS 342, Winter 2005 Lecture Notes
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
CSE 143 Lecture 7 Stacks and Queues reading: Stuart Reges notes on website slides created by Marty Stepp
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Building Java Programs
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
CMPT241 Web Programming Intro to JavaScript. Project 4.
CSE 154 LECTURE 6: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
CSE 143 Lecture 7 Stacks and Queues reading: "Appendix Q" (see course website) slides created by Marty Stepp and Hélène Martin
Lists in Python.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
CSE 143 Lecture 5 Stacks and Queues slides created by Marty Stepp
CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays.
CSE 154 LECTURE 17: JAVASCRIPT. Client-side scripting client-side script: code runs in browser after page is sent back from server often this code manipulates.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Built-in Data Structures in Python An Introduction.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
CSE 341 Lecture 29 a JavaScript, the bad parts slides created by Marty Stepp see also: JavaScript: The Good Parts, by.
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.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Svetlin Nakov Technical Trainer Software University Loops, Arrays and Strings Loops, Arrays, Associative Arrays and Strings.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
10 – Java Script (3) Informatics Department Parahyangan Catholic University.
CSE 341 Lecture 25 More about JavaScript functions slides created by Marty Stepp
Unit 12 JavaScript Arrays Instructor: Brent Presley.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming strings.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Working with Loops, Conditional Statements, and Arrays.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CSE 154 Lecture 6: Javascript.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
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.
Class02 More Arrays MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 1/14/2016.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
CSE 143 Lecture 11: Sets and Maps reading:
JavaScript and Ajax (JavaScript Arrays) Week 5 Web site:
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
CSE 154 LECTURE 15: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
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.
Intro to Javascript CS380.
CSE 341 Lecture 20 Mutation; memoization slides created by Marty Stepp
SEEM4570 Tutorial 05: JavaScript as OOP
>> JavaScript: Arrays
CSE 154 Lecture 6: Javascript.
Objectives Create an array Work with array properties and methods
ARRAYS MIT-AITI Copyright 2001.
slides created by Marty Stepp
String and Lists Dr. José M. Reyes Álamo.
JavaScript CS 4640 Programming Languages for Web Applications
Suggested self-checks: Section 7.11 #1-11
Lecture 5: Grid layout and Javascript
Introduction to Computer Science
Presentation transcript:

CSE 341 Lecture 24 JavaScript arrays and objects slides created by Marty Stepp

2 Arrays var name = []; // empty var name = [expr,..., expr]; // pre-filled name[index] // access value name[index] = expr; // store value var stooges = ["Larry", "Moe", "Shemp"]; stooges[2] = "Curly"; the array is the only data structure included in JavaScript (other than objects)

3 Array features JS arrays can store elements of multiple types: > var a = [42, true, "abc"]; arrays can be converted into strings (or call toString ): > print("hi " + a + " bye"); hi 42,true,abc bye caution: the typeof an array is object, not array: > typeof(a) object

4 Array length use the length property to find the # of elements: > a.length 3 you can set length ;  if smaller, truncates the array to the new smaller size  if larger, all new elements will be undefined > a.length = 2; > a 42,true

5 Non-contiguous arrays there is no such thing as an array out-of-bounds error  get an element out of bounds → undefined  set an element out of bounds → length increases to fit –any elements in between old/new lengths are undefined > var a = [42, 10]; > a[10] = 5; > a 42,10,,,,,,,,,5 > typeof(a[6]) undefined > a.length 11

6 Array instance methods.concat(expr...) returns new array with appended elements/arrays.indexOf(expr).lastIndexOf(expr) index of first/last occurrence of expr; -1 if not found.join(separator) glues elements together into a string.pop() remove and return last element.push(expr...) append value(s) to end of array.reverse() returns new array w/ elements in opposite order.shift() remove and return first element.slice(start, end) returns sub-array from start (incl.) to end (exclusive).sort().sort(compareFn) sorts array in place, with optional compare function that takes 2 values, returns 0 ( compareTo ).splice(index, count, expr...) Removes count elements from array starting at index, and inserts any given new elements there.toString() converts array to string such as "42,5,-1,7".unshift(expr...) insert value(s) at front of array

7 Array methods example var a = ["Stef", "Jay"]; // Stef, Jay a.push("Bob"); // Stef, Jay, Bob a.unshift("Kelly"); // Kelly, Stef, Jay, Bob a.pop(); // Kelly, Stef, Jay a.shift(); // Stef, Jay a.sort(); // Jay, Stef array serves as many data structures: list, queue, stack,... methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift  push and pop add / remove from back  unshift and shift add / remove from front – shift and pop return the element that is removed

8 Split and join var s = "quick brown fox"; var a = s.split(" "); // ["quick", "brown", "fox"] a.reverse(); // ["fox", "brown", "quick"] s = a.join("!"); // "fox!brown!quick" split breaks a string into an array using a delimiter  can also be used with regular expressions (seen later) join merges an array into a single string, placing a delimiter between them

9 "Multi-dimensional" arrays JS doesn't have true multi-dimensional arrays, but you can create an array of arrays: > var matrix = [[10, 15, 20, 25], [30, 35, 40, 45], [50, 55, 60, 65]]; > matrix[2][1] 55 > matrix.length 3 > matrix[1].length 4

10 (broken) for-each loop for (name in expr) { statements; } JavaScript has a "for-each" loop, but it loops over each index, not each value, in the array.  in some impl.s, it also loops over the array's methods!  considered broken; discouraged from use in most cases > var ducks = ["Huey", "Dewey", "Louie"]; > for (x in a) { print(x); } 0 1 2

11 Array exercises Write a function sum that adds the values in an array. Write a function longestWord that takes a string and returns the word within that string with the most characters. If the string has no words, return "". Write a function rotateRight that accepts an array and an integer n and "rotates" it by sliding each element to the right by 1 index, n times.  rotateRight([1, 2, 3, 4, 5], 2); changes the array to store [4, 5, 1, 2, 3]

12 Simulating other data structures JS has no other collections, but an array can be used as...  a stack: push, pop, length  a queue: push, shift, length  a list: push / pop / unshift / shift, slice / splice, indexOf...

13 Array higher-order methods * * most web browsers are missing some/all of these methods.every(function) accepts a function that returns a boolean value and calls it on each element until it returns false.filter(function) accepts a function that returns a boolean ; calls it on each element, returning a new array of the elements for which the function returned true.forEach(function) applies a "void" function to each element.map(function) applies function to each element; returns new array.reduce(function).reduce(function, initialValue).reduceRight(function).reduceRight(function, initialValue) accepts a function that accepts pairs of values and combines them into a single value; calls it on each element starting from the front, using the given initialValue (or element [0] if not passed) reduceRight starts from the end of the array.some(function) accepts a function that returns a boolean value and applies it to each element until it returns true

14 Objects simple types: numbers, strings, booleans, null, undefined  object-like; have properties; but are immutable  all other values in JavaScript are objects JavaScript objects are mutable key/value collections  a container of properties, each with a name and value JavaScript does not have the concept of classes (!!)  every object is "just an object"  (it is possible to relate one object to others; seen later)

15 Creating an object { name: expr, name: expr,..., name: expr }  can enclose name in quotes if it conflicts with a keyword > var teacher = { fullName: "Marty Stepp", age: 31, height: 6.1, "class": "CSE 341" }; > var emptyObj = {}; an object variable stores a reference to the object: > var refToTeacher = teacher; // not a copy

16 Accessing object properties object.propertyName object["propertyName"] object[expr]  use latter syntax if you don't know prop. name till runtime > teacher.age 31 > teacher["fullName"] Marty Stepp > var x = "height"; > teacher[x] 6.1

17 Modifying/removing properties object.propertyName = expr; object["propertyName"] = expr; delete object.propertyName; delete object["propertyName"];  delete removes a property from the object > teacher.age = 29; // if only... > teacher["height"] -= 0.2; > delete teacher.age; // no one will know! > typeof(teacher.age) undefined

18 More about properties property names can be anything but undefined : > var silly = {42: "hi", true: 3.14, "q": "Q"}; you can add properties to an object after creating it: > silly.favoriteMovie = "Fight Club"; > silly["anotherProp"] = 123; if you access a non-existent property, it is undefined: > silly.fooBar > typeof(silly.fooBar) undefined

19 Null/undefined objects trying to read properties of null/undefined is an error: > var n = null; > var u; // undefined > n.foo // error > u.foo // error You can guard against such errors with && and || : > teacher && teacher.name Marty Stepp > n && n.foo null > (n && n.foo) || 42 // 42 if n is falsey 42

20 Object methods an object can contain methods (functions) as properties  method can use the this keyword to refer to the object function greet(you) { print("Hello " + you + ", I'm " + this.fullName); } > teacher.greet = greet; > teacher.greet("students"); Hello students, I'm Marty Stepp

21 For-each loop on objects for (name in object) { statements; } "for-each" loops over each property's name in the object  it also loops over the objects's methods!  usually not useful; discouraged. also order unpredictable > for (prop in teacher) { print(prop + "=" + teacher[prop]); } fullName=Marty Stepp age=31 height=6.1 class=CSE 341 greet=function greet(you) { print("Hello " + you + ", I'm " + this.fullName); }

22 Objects as maps JS has no map collection, but an object can be used as one:  the "keys" are the object's properties (property names) > var phonebook = {}; > phonebook["Marty"] = " "; > phonebook["Stuart"] = " "; > phonebook["Jenny"] = " "; > phonebook["Stuart"] "Marty" "Jenny" "Stuart" " " " " " " keys (properties) values

23 Arrays are (just) objects an array is (essentially) just an object with properties named 0, 1, 2,..., and a length property  arrays also contain methods like pop and slice it's hard to tell whether a given value even IS an array  typeof({name: "Bob", age: 22}) → "object"  typeof([1, 2, 3]) → "object"

24 Duck typing duck typing: Dynamic typing where an object's set of properties, rather than its class, determines its semantics.  "If it walks like a duck, and quacks like a duck,..." JS code will "work" as long as a value is not used in a way that causes an error. Any JS parameter can be of any type, so a function that expects an array can be "tricked" by passing any object that "walks and quacks" like an array...

25 Duck typing in action function sum(a) { // add up elements of an "array" var total = 0; for (var i = 0; i < a.length; i++) { total += a[i]; } return total; } anything with length and numeric props. up to that length works: > var a1 = [3, 4, 5]; > sum(a1) 12 > var o1 = {0:42, 9:77, 1:8, length:2}; // quack > sum(o1) 50