JavaScript and Ajax JavaScript Data Types Week 2 Web site httpfogccsfeduhyip JavaScript Data Types Three primitive data types number internal represented as float number string boolean One composite data type ID: 772408
Download Presentation The PPT/PDF document "JavaScript and Ajax" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
JavaScript and Ajax(JavaScript Data Types) Week 2 Web site: http://fog.ccsf.edu/~hyip
JavaScript Data Types Three primitive data types number (internal represented as float number) string boolean One composite data type object (object, array, function) Four special values null (no value) undefined (variable declared, but no value assigned to it; object with property that does not exist) NaN (Not a Number) i nfinity (+ or – infinity)
Primitive Data Type - number Number System Base Example Decimal 10127Hexadecimal160x7F or 0X7FOctal 80177 Method Example Normal 12.000 -7.35 .552 Scientific notation 12E6 -.735E1 .552E0
Primitive Data Type - string A string is a sequence of Unicode letters, digits, punctuation characters, and so on Examples: "" 'Testing' "3.14" "Last 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. Escape sequence Description \0The null character\bBackspace\tHorizontal tab\n Newline \v Vertical tab \f Form feed \r Carriage return \" Double quote \' Apostrophe or single quote \\ backslash
Primitive Data Type – 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 var test = "this is a text"; test.length // length of string = 14 test.toUpperCase() // output string to uppercase, original data unchangedtest.toLowerCase() // output string to lowercasetest.substring(2,4) // extract chars from pos 2 to pos 3, starting pos zerotest.charAt(test.length – 1) // single chartest.indexOf("is") // find the first occurrence of is, 2test.indexOf("is", 3) // find "is" starting from position 3
Primitive Data Type - boolean The boolean data type has only two values: true and false true = 1, +/- number, non-empty string false = 0, NaN, "", null, undefinedBoolean value used as number context:var a = true; // what data type is a?var b = a + 1; // what is b?Boolean value used as string context:document.write(a); // display "true" or "false"
Primitive Data Type - boolean Number value used as boolean context: var num = 1; // what is the result? If num=0 or NaNif (num) { alert("true");} else { alert("false");}String value used as boolean context:var num = "abc"; // what is the result? If num = "" or null or undefined if ( num ) { alert("true"); } else { alert("false"); }
Data Conversion Number : var num = 4.5;Auto conversion from number to stringalert(num);document.write(num);Auto conversion from number to booleanif (num) { alert("true");} else { alert("false"); } Manual conversion from number to string alert( num.toFixed (2)); // what is the result? //4.50 alert( num.toExponential (2)); // 4.50E0 a lert( num.toPrecision (2)); //4.5
Data Conersion (continue…) String : var str1 = "21"; var str2 = "2";Auto conversion from string to number var result = str1 * str2; // other operators / - are ok too if (str2 == 2) { alert("true"); }Auto conversion from string to boolean if (str2) { alert("true"); } Manual conversion from string to number var num = parseInt (str1); var num2 = parseFloat (str2);
Data Conversion (continue…) Boolean : var bool = true; Auto conversion from boolean to number var result = bool + 2; if (bool == 1) { alert("true"); }Auto conversion from boolean to string alert(bool); document.write(bool);No Manual conversion
Composite Data Type - object Object is a composite data type which consists of properties and methods Dot notation: object_name.property_name object_name.method_name()Object creation:Special constructor (new operator):var obj = new Object();obj.x = 2.3;obj.y = 3.2;Object literal: var obj = { x:2.3, y:3.2};
Composite Data Type - array Array is a collection of data values (elements), each data value (element) in an array has an index (non-negative integer, starting from zero) Array creation With new operator: var a = new Array(); a[0] = 12; a[1] = "ABC"; a[2] = true;Declare and initialize at the same time:var a = new Array(12, "ABC", true);With array literal:var a = [12, "ABC", true];
Associative array In JavaScript, object and array are interchangeable Object creation: var obj = { x:2.3, y:3.2};Referencing object using dot notation:obj.x = 123;Referencing object using associative array format:obj["x"] = 123;
Composite Data Type - function Function is a piece of executable code <script> function function_name(argument, parameter) { // JavaScript code;}</script><script>// define JavaScript functionfunction square(x) { return x * x;}</script><script>// call user defined functionvar y = square(2);</script>
NaN var num = parseInt("abc"); // or use parseFloat()if (isNaN(num)) { alert("Not a number");} else { alert("It is a valid number");}
variable Variable is a symbolic name that represents a value that can and likely will change or vary during a program’s execution Normally, declare and initialize at the same time var n = 37;var a = "abc";var b = true;Variable name rules:Only letters, numbers, and underscore are valid charactersFirst character must be letter or underscoreCannot contain spacesNo reserved wordsIt is case sensitive
variable (continue…) Invalid variable Valid variable first-name first_name1namefirst_namelast namelast_namecasemyCaseifmyIf
Expression Expression will be evaluated to return a single value (single data type) var num = 27 + 2;First, 27 + 2 will be evaluated to become 29 with data type of numberThen, assign numeric 29 to variable num
Sum of two numbers JavaScript treats data in HTML text box as string data type even though it may contain number [See sum of two numbers sample ]
Sum of two numbers solution To fix the problem, converts the text/string data manually using parseInt () or parseFloat ()[See sum of two numbers solution]
Typeof operator Typeof operator determines the current data type of any variable var a = 123; var b = true;var c = "ABC";var result = typeof(a);