PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

Similar documents
Javascript Methods. concat Method (Array) concat Method (String) charat Method (String)

Chapter 4 Basics of JavaScript

COMS 469: Interactive Media II

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

CS1520 Recitation Week 2

UNIT-4 JAVASCRIPT. Prequisite HTML/XHTML. Origins

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 15: JavaScript loops, Objects, Events - Spring 2011

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

JavaScript I VP R 1. Copyright 2006 Haim Levkowitz. Outline

Note: Java and JavaScript are two completely different languages in both concept and design!

Chapter 1 Introduction to Computers and the Internet

4.1 Overview of JavaScript

More on new. Today s Goals. CSCI 2910 Client/Server-Side Programming. Creating/Defining Objects. Creating/Defining Objects (continued)

a Why JavaScript? jonkv interactivity on the web CGI JavaScript Java Applets Netscape LiveScript JavaScript 1: Example

CMPT 100 : INTRODUCTION TO

JavaScript: More Syntax and Using Events

introjs.notebook March 02, 2014

CECS 189D EXAMINATION #1

JavaScript Introduction

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

About the Tutorial. Audience. Prerequisites. Copyright and Disclaimer

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

By the end of this section of the practical, the students should be able to:

The first sample. What is JavaScript?

Introduction to JavaScript

JavaScript Basics. The Big Picture

PIC 40A. Review for the Final. Copyright 2011 Jukka Virtanen UCLA 1 06/05/15

AP Computer Science A

<form>. input elements. </form>

Session 16. JavaScript Part 1. Reading

ORB Education Quality Teaching Resources


CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging

Programming language components

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

c122mar413.notebook March 06, 2013

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

Information Design. Professor Danne Woo! infodesign.dannewoo.com! ARTS 269 Fall 2018 Friday 10:00PM 1:50PM I-Building 212

Chapter 12. JavaScript 1: Basic Scripting Table of Contents

PIC 40A. Lecture 4b: New elements in HTML5. Copyright 2011 Jukka Virtanen UCLA 1 04/09/14

Lecture 2. The variable 'x' can store integers, characters, string, float, boolean.

Try the following example using the Try it option available at the top right corner of the below sample code box

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript

ID1354 Internet Applications

Chapter 2 Working with Data Types and Operators

Lesson 7: If Statement and Comparison Operators

Coding in JavaScript functions

Client-Side Web Technologies. JavaScript Part I

Handout 7. Defining Classes part 1. Instance variables and instance methods.

JAVASCRIPT BASICS. JavaScript String Functions. Here is the basic condition you have to follow. If you start a string with

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

PIC 40A. Lecture 19: PHP Form handling, session variables and regular expressions. Copyright 2011 Jukka Virtanen UCLA 1 05/25/12

Microsoft Excel 2010 Training. Excel 2010 Basics

Scripting for Multimedia LECTURE 3: INTRODUCING JAVASCRIPT

Exercise 1: Basic HTML and JavaScript

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

<script type="text/javascript"> script commands </script>

HTML5 and CSS3 More JavaScript Page 1

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

Java Classes and Objects

Session 6. JavaScript Part 1. Reading

Programming with Java

Programing for Digital Media EE1707. Lecture 3 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

CSc 337 LECTURE 5: GRID LAYOUT AND JAVASCRIPT

JavaScript by Vetri. Creating a Programmable Web Page

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

Programming Language 2 (PL2)

JavaScript s role on the Web

More About Objects and Methods

Such JavaScript Very Wow

A variable is a name for a location in memory A variable must be declared

Add Subtract Multiply Divide

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

What did we talk about last time? Math methods boolean operations char operations

Bitwise Operators Objects and Methods

CSC 160 Introduction to Programming for Non-majors. Lecture 4 - Looping Around Loops I: Counting Loops. Why loops?

JAVASCRIPT. Ajax Technology in Web Programming. Sergio Luján Mora. DLSI - Universidad de Alicante 1. Basic syntax and features

Web Programming/Scripting: JavaScript

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CSC Web Programming. Introduction to JavaScript

var num1 = prompt("enter a number between 1 and 12","1"); var promptstring = "What is " + num1 + " times 3?"; var num2 = prompt(promptstring);

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

CSE 341 Section Handout #6 Cheat Sheet

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Using Java Classes Fall 2018 Margaret Reid-Miller

JavaScript: Introduction, Types

Contents. Osp::Base::Object Osp::Base::String Osp::Base::Buffer Osp::Base::DateTime

Types and Expressions. Chapter 3

CS261: HOMEWORK 2 Due 04/13/2012, at 2pm

Chapter 7: JavaScript for Client-Side Content Behavior

Voice Application Specification. SBString

ECE 122. Engineering Problem Solving with Java

PIC 40A. Midterm 1 Review

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Outcomes Week 2 Overview Describe the inputs, activities, and outputs of each step in the software development life cycle. Describe arithmetic, relati

Transcription:

PIC 40A Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers 04/24/17 Copyright 2011 Jukka Virtanen UCLA 1

Objects in JS In C++ we have classes, in JS we have OBJECTS. We will not study how to make objects in this course, but we will use a lot of predefined objects. Objects can have methods and properties. Method is like a member function of a class and property is like a data variable stored by the class. 04/24/17 Copyright Jukka Virtanen 2011 2

Objects in JS Example: document.write("hello world!"); Here document is an object and write is a method. We will see many more examples of properties and methods in weeks to come. 04/24/17 Copyright Jukka Virtanen 2011 3

Recall JavaScript has primitive data types Number String Boolean Each of these data types have corresponding wrapper objects: Number, String, Boolean. Confused yet? 04/24/17 Copyright Jukka Virtanen 2011 4

Wrapper objects Wrapper objects are predefined objects that have useful methods and properties. Lets say that I have a string variable var name= Fry ; String variable by itself is just an ordinary variable that has no methods or properties. However it can be coerced to its corresponding wrapper String object and then it gains methods and properties. 04/24/17 Copyright Jukka Virtanen 2011 5

Example var name= Fry ; var len = name.length; No parenthesis. length is a property! document.write(name + has + len + letters ); Ordinary string variables like name do not have properties, but here name is coerced into its wrapper object. 04/24/17 Copyright Jukka Virtanen 2011 6

String wrapper object String wrapper object has the length property and the following methods: Method Parameters What does it do charat A number returns the char at the specified position. indexof One character string Returns the location of the specified character. substring Two numbers. Start index is first, second is index of end+1. Returns the substring of the string object from the first paramer to the second. tolowercase None Converts the string to lowercase touppercase None Converts the string to oppercase 04/24/17 Copyright Jukka Virtanen 2011 7

String examples var name = Philip J. Fry ; var first_name = name.substring(0,6); var letter = name.charat(7); // J var index = name.indexof(. ); // 8 04/24/17 Copyright Jukka Virtanen 2011 8

Number wrapper object Number object has method tostring which we discussed earlier. It has some properties as well: MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY,PI. These properties are for your reference only you will not be quizzed on them. 04/24/17 Copyright Jukka Virtanen 2011 9

Math object Math object is a predefined object. All of Math objects methods are referenced through the Math object. Example: var value = Math.sin(x); // Here x is of type number Some useful math methods include: sin, cos, floor, ceil, abs, exp, pow(x,y). See web for complete reference. 04/24/17 Copyright Jukka Virtanen 2011 10

The Date object On the web displaying information about date or writing code that depends on date or time information is common. Date object is not a predefined object! You have to invoke a constructor for the Date object. The constructor is predefined for you. var today = new Date(); 04/24/17 Copyright Jukka Virtanen 2011 11

Date object methods Method tolocalestring getdate Returns A string of Date information The day of the month getmonth The month of the year in range 0 to 11 getday Day of the week in range 0 to 6 getfullyear gettime The year Number of seconds since unix dawn of time (Jan. 1 1970) gethours Hour in the range 0 to 24 getminutes Minute in the range 0 to 59 getseconds Seconds in the range 0 to 59 getmilliseconds Number in the range 0 to 999 04/24/17 Copyright Jukka Virtanen 2011 12

Date Examples <script type="text/javascript"> <!-- // Create Date object initialized to time right now var today = new Date(); //Extract some info var date_string = today.tolocalestring(); var day = today.getday(); var month = today.getmonth(); var year = today.getfullyear(); //Write some stuff on the screen document.write ("<h1>welcome to my website!</h1> <h1> Today is: " + date_string + "</h1>"); document.write ("Day: " + day + "<br/>"); document.write ("Month: " + month + "<br/>"); document.write ("Year: " + year + "<br/>"); document.write ("How long does it take you to count to 10000000?<br/>"); //Get start time var start = new Date(); //Loop! for (var i = 0; i < 10000000; i++); //Ok what is the time after the looping var end = new Date(); //Difference is how long the loop took var diff = end.gettime() - start.gettime(); //Write the result document.write ("I can do it in " + diff + " milliseconds!!"); // --> </script> 04/24/17 Copyright Jukka Virtanen 2011 13

JavaScript Input and Output document.write(... ); Examples: var a="hello world!"; document.write(a); document.write("hello World"); In general document.write(any_variable); or document.write(any_literal); 04/24/17 Copyright Jukka Virtanen 2011 14

document.write(... ); cont. even more generally document.write("the value of my_number is: ", my_number, "<br/>"); multiple values are concatenated. But you can just concatenate yourself too! document.write("the value of my_number is: " + my_number + "<br/>"); So it is not so useful to give multiple arguments after all. 04/24/17 Copyright Jukka Virtanen 2011 15

alert An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax: alert(some_string_paramater); some_string_paramater should not be XHTML So the string parameter could include \n but not <br/> Example: alert("the sum is:" + sum + "\n"); 04/24/17 Copyright Jukka Virtanen 2011 16

confirm The confirm function opens a dialog box with a message and an Ok button and a Cancel button. A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. Confirm returns either true if user presses Ok or false if user presses Cancel Example: var exit_question = confirm ("Are you sure you want to exit?"); 04/24/17 Copyright Jukka Virtanen 2011 17

prompt Prompt function is a great way to have user input data The prompt function opens a dialogue box that contains a text box that can be used to get a string of input from the user Prompt box also has an Ok and Cancel buttons prompt function takes two arguments: The string used as a message in the box and a default value for the text box. Often empty string is used as default value Example: name = prompt("what is your name?", ""); 04/24/17 Copyright Jukka Virtanen 2011 18

Control Statements A program s flow is the order of execution of the program s statements. Control statements determine flow based on values of control expressions or conditions. Examples of control statements: selection statements if-then, if-then-else, switch loop statements while, do-while, for, for-in 04/24/17 Copyright Jukka Virtanen 2011 19

Control expressions can be primitive values relational expressions function calls object references compound expressions formed with any of the above by using logical operators such as! && Anything that is or can be coerced to a Boolean primitive value 04/24/17 Copyright Jukka Virtanen 2011 20

Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true x==="5" is false!= is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true 04/24/17 Copyright Jukka Virtanen 2011 21

How are comparison operators used? They are used to form boolean expressions which can be used as control expressions. Example: if (my_number > your_number) document.write("sorry, you lose."); 04/24/17 Copyright Jukka Virtanen 2011 22

Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true or (x==5 y==5) is false! not!(x==y) is true 04/24/17 Copyright Jukka Virtanen 2011 23

if Statement if (condition) { // code to be executed if condition is true } Example: <script type="text/javascript"> var weather=""; weather = prompt("how is the weather?"); if (weather=="raining") alert("you better bring an umbrella."); </script> For compound statements use if(...){ } For single statement if(...) statement; is ok 04/24/17 Copyright Jukka Virtanen 2011 24

Example Change the style sheet for the website depending on time of day. var now = new Date().getHours(); if (0 <= now && now < 5) document.write("<link rel='stylesheet' href='night.css' type='text/css'>"); if (5 <= now && now < 11) document.write("<link rel='stylesheet' href='morning.css' type='text/css'>"); if (11 <= now && now < 16) document.write("<link rel='stylesheet' href='day.css' type='text/css'>"); if (16 <= now && now < 22) document.write("<link rel='stylesheet' href='evening.css' type='text/css'>"); if (22 <= now && now <= 24) document.write("<link rel='stylesheet' href='night.css' type='text/css'>"); 04/24/17 Copyright Jukka Virtanen 2011 25

if else if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is not true } Example: var d = new Date(); var time = d.gethours(); if (time < 10) { document.write("good morning!"); } else { document.write("good day!"); } 04/24/17 Copyright Jukka Virtanen 2011 26

if else if...else if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition1 is not true and condition2 is true }... else { // code to be executed if none of the conditions above are not true } 04/24/17 Copyright Jukka Virtanen 2011 27

Example var score = -1; score = prompt("enter your score"); if ( score >= 90 ) alert( "Your grade is A.\n Good work!"); else if ( score >= 80 ) alert("your grade is B."); else if ( score >= 70 ) alert("your grade is C."); else if (score >= 60 ) alert("your grade is D."); else alert("you fail.\n See you again next quarter!"); 04/24/17 Copyright Jukka Virtanen 2011 28

while loop The while loop loops through a block of code while a specified condition is true. while (condition) { // code to be executed } Example: <body> <script type="text/javascript"> var i=1; while(i<=6) { document.write("<h" + i + ">" + "This is header <h" + i + ">" + "</h" + i + ">"); i++; } </script> </body> 04/24/17 Copyright Jukka Virtanen 2011 29

for loop The for loop is used when you know in advance how many times the script should run. for (var i = startvalue; i <= endvalue; i += increment) { // code to be executed } See example 04/24/17 Copyright Jukka Virtanen 2011 30

How are comparison operators used? They are used to form boolean expressions which can be used as control expressions. Example: if (my_number > your_number) document.write("sorry, you lose."); 04/24/17 Copyright Jukka Virtanen 2011 31

How are comparison operators used? They are used to form boolean expressions which can be used as control expressions. Example: if (my_number > your_number) document.write("sorry, you lose."); 04/24/17 Copyright Jukka Virtanen 2011 32

do-while JavaScript has a do-while loop that works exactly like C++ do-while. Example: var i=0; do { //stuff i+=2; }while(i<20); 04/24/17 Copyright Jukka Virtanen 2011 33

Random numbers To get a random number in the range 0.0 up to but not including 1.0 we can write: var my_random_number = Math.random(); To get numbers in the range we want we have to use combination of multiplication addition and floor math functions. Example: Simulate a dice roll. var dice = Math.floor( 1 + Math.random() * 6 ); Explanation: First we get a random number in the range 0 up to but not including 6 then we add one so we have a random number in the range 1 up to but not including 7. Then we floor it so we have an integer in the range 1 to 6 inclusive. 04/24/17 Copyright Jukka Virtanen 2011 34

Is the random number generator seeded? Yes it is seeded automatically. 04/24/17 Copyright Jukka Virtanen 2011 35

General formula for integers var number = Math.floor ( a + Math.random() * (b-a+1) ); This gives an integer in the range [a,b]. The scaling factor is b and the shifting value is a. 04/24/17 Copyright Jukka Virtanen 2011 36