Tutorial slides

Download Report

Transcript Tutorial slides

COMP 4901F
Data Visualization
Lab 1 Basics of Javascript
Yuanzhe Chen (Aaron)
Dept CSE, HKUST
Javascript
Javascript has nothing to do with Java, the name is
only for marketing purpose.
A programing language for web browser.
C style syntax, but related to functional
programming.
Data Types
Numbers: 1, 1.23456…
Logical: true, false
Strings: “Hello world”, ‘Hello world’
Arrays
null, undefined
Objects
Functions
Data Types
Numbers: 1, 1.23456…
var a = 5;
Logical: true, false
var a = true;
Strings: “Hello world”, ‘Hello world’
var a = “Hello”;
var a = “Hello” + “World”;
var a = 4 + “ever”;
Arrays
var a = [1, 2, 3, “hello”]; //a[3] = “hello”
Data Types
null, undefined
var a = null;
var a = undefined;
var a; //The value of a is undefined;
Objects
var student = {
name: “Tony”;
gender: “male”;
};
student.name;
//everything except null and undefined can be
treated as objects!
Data Types
Functions
One way:
function myfunc(d, n){
//……
};
Another way:
var myfunc = function(d, n){
//……
};
//function can be a variable!
Object Oriented Programing
var student = function(){
name: “Tony”;
gender: “male”;
};
student.prototype.setName = function(d){
this.name = d;
}
//can not use student = {name: “Tony”; gender:
“male”}, user Object.prototype instead.
Control Flow
C-style Control Flow:
for, while, if/else, switch/case, continue,
break……
Include Javascript code
Inline:
<script>
//code
</script>
Include
<script src=“code.js”></script>
Scripting HTML
document.getElementById(“”).innerHTML
<p id="demo"></p>
document.getElementById("demo").innerHTML =
“hello world”;
//More details later
Debugging your code
console.log(d);
Your task
1. Download the skeleton code
2. Generate an random array. (already provided in the
code)
3. Finish the function of calculating average of an
array.
4. Display both the elements in the array and the
result on the webpage.
More resources
http://www.w3schools.com/js/default.asp
http://courses.cs.washington.edu/courses/cse512/14
wi/d3-tutorial/fundamental.html#/
http://bonsaiden.github.io/JavaScript-Garden/
http://eloquentjavascript.net/