CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Data Types.

30
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Data Types

Transcript of CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Data Types.

CNIT 133 Interactive Web Pags –JavaScript and AJAX

JavaScript Data Types

Agenda

• My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes).

• Datatypes and values• Numbers• Strings• Boolean values• Functions• Objects• Arrays

JavaScript Data Types

• JavaScript supports three primitive data types (number, string, and boolean), and one composite data type (object).

• Primitive = cannot get any simpler.• Composite = it is make up of a combination of

data (various types).• JavaScript recognizes four special values:

null undefined NaN Infinity

JavaScript Data Types (continue…)• JavaScript supports a composite datatype known as an object• An object (member of datatype object) represents a collection of values

(primitive values or another object)• Objects in JavaScript have a dual nature: an unordered collection of named

values or an ordered collection of numbered values (array)• JavaScript defines another special kind of object, known as a function. A

function is an object that has executable code associated with it• JavaScript defines a few other specialized kinds of objects (new classes of

objects) The Date class defines objects that represent dates The RegExp class defines objects that represent regular expressions The Error class defines objects that represent syntax and runtime errors that can

occur in a JavaScript program

Numbers

• JavaScript does not make a distinction between integer values and floating-point values. All numbers are represented as floating-point values

• JavaScript represents numbers using the 64-bit (8-byte) floating-point format defined by the IEEE 754 standard

• When a number appears directly in a JavaScript program, it is called a numeric literal

• Special numeric values: Infinity and NaN

Numbers (continue…)• Integer literals (base-10): -9007199254740992 (-2

power of 53) to 9007199254740992 (2 power of 53)• Hexadecimal literals (base-16): begins with 0x or 0X,

followed by a string of hexadecimal digits ( 0-9, A – F). (e.g. 0xff, 0XCAFE911)

• Although the ECMAScript standard does not support Octal literals (base-8), some implementations of JavsScript allow Octal literals: begins with the digit 0 and followed by a sequence of digits, between 0 to 7 (e.g. 0377)

• Since some JavaScript support Octal literals, you should never write an integer literal with a leading zero

Numbers (Integer Bases)Number System Base Notation Example

decimal 10 Enter the number as a normal integer without a leading 0 (zero).

127

hexadecimal 16 Enter the number as an integer with a leading 0x (zero x) or 0X (zero X).

0x7F or 0X7F

octal 8 Enter the number as an integer with a leading 0 (zero)

0177

Numbers (Floating-Point)

• Syntax: [digits][.digits][(E|e)[(+|-)]digits]Method Notation Example

normal Enter the number as a decimal integer followed by a decimal point (.) and a fraction expressed in decimal.

12.000

-7.35

.552

scientific notation Enter the number as a decimal integer followed by an exponent indicator (E) and an integer that can be signed (preceded by a “+” or “-”).

12E6

-.735E1

.552E0

String• A string is a sequence of Unicode letters, digits, punctuation

characters, and so on• String literals: a sequence of zero or more Unicode characters

enclosed within single or double quotes (' or ").• String literals must be written on a single line (if you need to include a

newline character, use the character sequence \n)• To represent a single character, you simply use a string that has a

length of 1• Examples:

" "'testing'"3.14"'name="myform " '"his name is O’Riley""this string has \n two lines"

Escape Sequence• Escape sequence in string literals: the backslash character (\) has a

special purpose in JavaScript strings. Combined with the character that follows it, it represents a character that is not otherwise representable within the string. (e.g. ' you\ 're right' )

• JavaScript escape sequences\0 The NULL character\b backspace\t horizontal tab\n newline\v vertical tab\f form feed\r carriage return\” double quote\’ apostrophe or single quote\\ backslash

String (continue …)

• Creating a String object:var test = "this is a text";var test = new String("this is a text");

• Concatenate strings:var msg = "Hello, " + "world"; //produce "Hello, world"var greeting = "Welcome" + " " + msg;

String Methods• Examples of string methods:

var test = "this is a text";test.length // length of string = 14test.toUpperCase() // change string to uppercase, not physically re-save the data. The

result is - "THIS IS A TEXT"test.toLowerCase() // change string to lowercasetest.substring(2,4) // extract pos 2 to pos 3, starting pos is always zero. The result is - "is"test.charAt(test.length – 1); // single char, last char of this string. The result is - "t"test.indexOf("is") // find first occurrence of "is“. The result is - 2test.indexOf("is", 3) // find occurrence of "is“, starting from pos 3. The result is - 5

Converting numbers to strings

• Converting numbers to strings: numbers are automatically converted to strings when needed String concatenation expression:

var n = 100;var s = n + " bottles of beer on the wall. ";var n_as_string = n + "";

Converting Numbers to Strings (continue…)

• A shortcoming of JavaScript prior to JavaScript 1.5 is that there is no built-in way to convert a number to a string and specify the number of decimal places to be included, or to specify whether exponential notation should be used

• ECMAScript v3 and JavaScript 1.5 solve this problem by adding three new number-to-string methods to the Number class: toFixed(), toExponential(), and toPrecision():

var n = 123456.789;n.toFixed(0); // 123457n.toFixed(2); // 123456.79n.toExponential(1); // 1.2e+5n.toExponential(3); // 1.235e+5n.toPrecision(4); // 1.235e+5n.toPrecision(7); // 123456.8

Converting Strings to Numbers

• Converting strings to numbers: when a string is used in a numeric context, it is automatically converted to a number

var product = "21" * " 2"; // 42 is the product of #var number_value = string_value – 0;

• Use Number() constructor as a function:var number_value = Number(string_value);The trouble with this sort of string-to-number conversion is that it

works only with base-10 numbers, it allows leading and trailing spaces, it does not allow any non space characters to appear in the string following the number

Converting Strings to Numbers (continue…)

• To allow more flexible conversions, use parseInt() and parseFloat(). These functions convert and return any number at the beginning of a string, ignoring any trailing non-numbers.

• parseInt() parses only intergers.• parseFloat() parses both integers and floating-point numbers. • If a string begins with 0x or 0X, parseInt() interprets it as a hexadecimal number

parseInt("3 blind mice"); // returns 3parseFloat("3.14 meters"); // returns 3.14parseInt("12.34"); // returns 12parseInt("0xFF"); // returns 255

• parseInt() can take a second argument specifying the radix (base) of the number to be parsed. (base between 2 to 36)

parseInt("11", 2); // returns 3 (1*2 + 1)parseInt("ff", 16); // returns 255parseInt("077", 8); // returns 63parseInt("eleven"); // returns NaNparseFloat("$72.47"); // returns NaN

Boolean• The Boolean data type has only two values: true and false.• Some languages, like C, do not have a specific Boolean or logical data

type. Instead, they often use the integers 1 (TRUE) and 0 (FALSE) to represent truth and false values. JavaScript, however, does recognize Boolean as a distinct data type.

• Boolean values are generally the result of comparisons in your JavaScript programs

(a == 4) // it will be determined to be true or false

• Boolean values are typically used in JavaScript control structuresif (a == 4) { b = b + 1;} else { a = a + 1;}

Boolean (continue…)• Boolean type conversions: boolean values are often automatically converted

If boolean value is used in a numeric context, true converts to the number 1, and false converts to the number 0

var num1 = true;var newNum = num1 + 1; //newNum = 2

If boolean value is used in a string context, true converts to the string “true”, and false converts to the string “false”

document.write(num1); //display "true" If a number is used where a boolean value is expected, the number is

converted to true unless the number is 0 or NaN, which are converted to fasevar num = 1;if (num) {

//num is 1 or > 1} else {

//num is 0 or NaN}

Boolean (continue…) If a string is used where a boolean value is expected, it is converted to true

except for the empty string, null and undefined, which will converted to false. Any non-null object, array, or function converts to true

var num1 = "abc";if (num1) {

//string is not null} else {

//empty string or undefined}

Function• A function is a piece of executable code that is defined by a

JavaScript program or predefined by the JavaScript implementation.

• A function may be passed arguments, or parameters, specifying the value or values upon which it is to perform its computation, and it may also return a value that represents the results of that computation

function square(x) { return x * x;

}

var y = Math.sin(20); // predefined function var z = square(2);

Object

• An object is a composite data type.• It does not hold just one primitive type of data

value, such as number, string, or Boolean. Instead it is composed of zero or more pieces of data, each of which may be of a different basic data type.

Object (continue…)• An object is a collection of named values. These named values are

usually referred to as properties of the object.• To refer to a property of an object, you refer to the object, followed by

a period and the name of the property.image.width

image.height• Properties of objects can contain any type of data, including arrays,

functions, and other objects.document.myform.button

This code refers to the button property of an object that is itself stored in the myform property of an object named document.

Object (continue…)

• When a function value is stored in a property of an object, that function is often called a method, and the property name becomes the method name.

• To invoke a method of an object, use the . (period) syntax to extract the function value from the object and then use the () syntax to invoke that function.

document.write("this is a test"); // To invoke the write() method of an object named document.

Creating Object

• Creating objects: objects are created by invoking special constructor functions

var o = new Object();var now = new Date();

• Once you have created an object of your own, you can use and set its properties:

var point = new Object();

point.x = 2.3;point.y = 1.2;

Array• An array is a collection of data values, each data value in an array has a

number, or index.• In JavaScript, you retrieve a value from an array by enclosing an index in

square brackets after the array name. ( a[i] i is an non-negative integer, a[0], a[1])

• Array may contain any type of JavaScript data, including references to other arrays or to objects or functions:

document.images[1].width //This code refers to the width property of an object stored in the second element of an array stored in the images property of the document object.

• The regular arrays are indexed by non-negative integers. Associative arrays are indexed by strings

• JavaScript does not support multidimensional arrays, except arrays of arrays.

• The elements of an array do not all need to be of the same type.

Array (continue…)• Creating arrays: arrays can be created with the Array() constructor

function. Once created, any number of indexed elements can easily be assigned to the array.

var a = new Array();a[0] = 1.2;a[1] = "JavaScript";a[2] = true;a[3] = { x:1, y:3 };

• Arrays can also be initialized by passing array elements to the Array() constructor:

var a = new Array(1.2, "JavaScript", true, { x:1, y:3 });• If you pass only a single number to the Array() constructor, it specifies

the length of the arrayvar a = new Array(10); // Creates a new array with 10 undefined elements

Special Value - null

• The JavaScript keyword null is a special value that indicates no value.

• When a variable holds the value null, you know that it does not contain a valid object, number, string, or boolean value.

• When null is used in a Boolean context, it converts to false

• When used in a numeric context, it converts to 0• When used in a string context, it converts to "null".

Special Value - undefined• Undefined is returned when you use either a variable that has been declared but

never had a value assigned to it or an object property that does not exist. (this special undefined value is not the same as null).

• When reference to a variable that never be defined, JS will return error.var a; alert(a); // return undefinedalert(b); // never declare b, therefore, JS error

• Although null and the undefined value are distinct, the == equality operator considers them equal to one another:

my.prop == null //This comparison is true if either the my.prop property does not exist or it does exist but contains the value null. However, if you truly must distinguish between a null value and an undefined value, use the === identity operator or the typeof operator.

• When the undefined value is used in a Boolean context, it converts to false.• When used in a numeric context, it converts to NaN.• When used in a string context, it converts to "undefined".

Special Value - infinity

• Infinity is a numeric value representing positive or negative infinity.

• Mathematical computations that result in a infinity or undefined value, such as number divided by zero.

var n=30; alert(n/0); // returns Infinity

• Infinity is displayed when a number is higher than 1.7976931348623157E+10308

• - Infinity is displayed when a number is lower than - 1.7976931348623157E+10308

Special Value - NaN

• NaN is special value indicating that the result is "Not a number".