JS算法代写-EECS1012
时间:2021-08-03
07/07/2021
1
EECS1012
SU 2021
July 7, 2021 Lecture 8.
Net-Centric Introduction
to Computing
EECE1012
Net-Centric Introduction toComputing
JavaScript Review and more
variable, type
operators
Strings
Arrays
Boolean expression, and Control
Functions
Object math,date, object
Global variables
1
2
07/07/2021
2
Variables
 variables are declared with the var keyword (case
sensitive)
 types are not specified, but JS does have types
("loosely typed")
▪ Primitive: Number, Boolean, String,
▪ Composite: Array, Object, Function,
▪ Special: Null, Undefined
▪ can find out a variable's type by calling typeof
3
var name = expression; JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4; JS
JS variables
2
▪ variables are used to store and retrieved data.
▪ variables are defined by the keywords var (and let)
▪ variables are categorized into different data types
▪ first character must be a letter or an underscore (_)
❑ cannot be a number
▪ the rest of the variable name can be any letter, number,
or underscore
▪ variable names are case sensitive
❑ age,Age, AGE would all be different variable names
▪ you cannot use JSreserved words for variable names
❑ ?
3
4
07/07/2021
3
variable name examples
• valid names:
_myVar thissisalongvariablename num
_var eecs1012 myString
name1 test_1 X
• invalid names:
/* starts with a number */
/* there is a space in the name */
1test
test 1
t$est
var
/* non alphanumeric character */
/* reserved word */
3EECS 1012 – York University
JSdata types
4
TYPE Explanation Example
number Integers and numbers with decimal places. 99,2.8,5, -10
string A variable that can hold a collection of
characters.Sometimes we call this a
string literal.
"Hello","EECS1012"
boolean A variable that holds only two possible values
– true or false.
true or false
undefined When a variable does not have a value var x;
Objects Objects are special data types that have
functions and data associated with them.
These are more common in JS than PHP and
we will need to use them often.
document.getElementById();
(example of an object)
function A user defined function that can be called by a
user event (e.g.mouse click, etc)
function name ()
{
statements;
...
}
var x= 5;

x="Hi“;
Dynamic type
5
6
07/07/2021
4
Relation to computational thinking
w = prompt();
h = prompt();
s = w + h;
alert("sum", s)
number type variables
var enrollment = -99;
var medianGrade = 70.8;
var credits = 5 + 4 + (2 * 3);
• number types are integers (whole numbers) and
numbers with decimal places
• numbers with decimal places are often called
"floating point" numbers, e.g.:
2.99993 3000.9999 -40.00
we call them floating point because the decimal point appears to
float around. Sometimes these are just called floats to distinguish
them from integers.
8EECS 1012 – York University
• Use var as much as possible, making it local to the function
Math.sqrt(2)*Math.sqrt(2);
7
8
07/07/2021
5
expressions and statements
var num2 = num1 + 10; /* num1 + 10 is the expression,
/* this computes 5 + 10 */
num2 = num2 + 1; /* this uses num2 and assigns the
result back to num2 */
var str1 = "hello";
var str2 = "world";
num1 = ((3.14) * 10.0) / 180.0;
/* value is "hello" */
/* value is "world" */
/* multiple operators */
• an expression is the combination of one or more variables,
values, operators, or functions that computes a result.
var num1 = 5; /* value 5 is the expression */
9EECS 1012 – York University
Syntax breakdown of a statement
9
10
07/07/2021
6
Relation to computational thinking
basic arithmetic operators
a + b Addition Sum of a and b.
a - b Subtraction Difference of a and b.
a * b Multiplication Product of a and b.
a / b Division Quotient of a and b.
a % b Modulo Remainder of a divided by b.
here, a and b could be variables, but we could also replace them with
numbers, expressions.
10 + 20, 3.14 / 2.0, 10 + (5*6+7) etc.. .
12EECS 1012 – York University
11
12
07/07/2021
7
“short hand” assignment operators
assignment same as meaning
a += b; a = a + b; Addition
a -= b; a = a - b; Subtraction
a *= b; a = a * b; Multiplication
a /= b; a = a / b; Division
a %= b; a = a % b; Modulus
a++; a = a + 1; Self Addition
a--; a = a - 1; Self Subtraction
13EECS 1012 – York University
a -= 1
for(var i = 0; i < 100; i++)
……
Don’t use in
flow charts
“short hand” assignment operators
assignment same as meaning
a += b; a = a + b; Addition
a -= b; a = a - b; Subtraction
a *= b; a = a * b; Multiplication
a /= b; a = a / b; Division
a %= b; a = a % b; Modulus
a++; a = a + 1; Self Addition
a--; a = a - 1; Self Subtraction
14EECS 1012 – York University
a -= 1
for(var i = 0; i < 100; i++)
……
Don’t use in
flow charts
13
14
07/07/2021
8
js math operator precedence
var num1 = 5 * 5 + 4 + 1 / 2;
var num2 = 5 * (5 + 4) + 1 / 2;
console.log(num1 + "and" + num2);
// What is the answer?
// What is the answer?
JS
Operator Precedence:
( )
* / %
+ -
Highest
Lowest
29.5 and 45.5
output
* this operator precedence is the same for most programming languages.
15EECS 1012 – York University
Example from previous slide
15
16
07/07/2021
9
string type variables
• strings are treated like a series of characters
var favoriteFood = "falafel";
var stringNumber = "234";
Here,variable stringNumber is not the value two hundred
and thirty four,but instead the characters 2,3,4.
var len = stringNumber.length; // len is assigned the number 3
• string variables have a special property called "length" that returns
the number of characters in the string.
• keep in mind that spaces are also characters.
• var stringNumber = "2 34";
19EECS 1012 – York University
favoriteFood.length ?
stringNumber.length ?
17
19
07/07/2021
10
string as an object
var s1 = "Connie Client";
var len = s1.length; ?
variable s1 is of
type String, however,
this can also be thought
of as a "String object".
we can access various properties
of the object using a "." operator and
object's the property's name.
you will see this type of property access
often in JS (and other "Object Oriented"
languages)
20EECS 1012 – York University
more on strings
• you need to put quotes around a string to let JS know
it is a string. You can also use single quotes.
var s = "EECS1012"; // CORRECT!
var s = 'EECS1012'; // CORRECT!
var s = EECS1012; // INCORRECT!
In this example, JS will interpret EECS1012
as a variable, not a string!
21EECS 1012 – York University
var s = "EECS1012'; // INCORRECT!
20
21
07/07/2021
11
special characters
• what if you want a quote character " to be part of the
string?
var s = "use " for quote."; //INCORRECT!
this statement will cause problems for JS, because when it sees
the second double quote it will assume this is the end of the
string.
22EECS 1012 – York University
escape characters
• escape characters are used inside strings to tell JS how to
interpret certain characters
var s = "Use \" for quote."; //CORRECT
this string will be interpreted in JavaScript as:
Use " for quote.
here, a - is used to separated characters.
an underscore _ is used to represent a
space character.
23EECS 1012 – York University
22
23
07/07/2021
12
alternatives
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
you can use quotes inside a string, as long as they
don't match the quotes surrounding the string.
24EECS 1012 – York University
var answer = 'He is called "Johnny' ";
More escape characters
Code Result
\" quote
\' single quote
\n New Line
\\ Backslash
\t Horizontal Tabulator
examples:
var x = 'It\'s alright.';
var x = "We are the so-called \"Vikings\" from the north.";
var x = "The character \\ is called backslash.";
var x = "This string ends with a new line \n";
25EECS 1012 – York University
24
25
07/07/2021
13
string concatenation (+ operator)
var s1 = "Hello ";
var s2 = "World";
var s3 = s1 + s2; // s3 = "Hello World";
• the + operator is used for string concatenation
• this can be confusing,because we often think of + as only
being used for arithmetic.But,in this case of String types,it
means connect (or concatenate) two strings together.
26EECS 1012 – York University
more string + examples
var
var
var
s1
s2
s3
=
=
=
"";
"Alice";
"Kwong";
// empty string
var s4 = S1 + s2; // result "Alice", why? s1 is empty
var s5 = S2 + s3; // result "AliceKwong"
var s6 = S2 + " " + s3; // Result "Alice Kwong"
// why "Alice" + " " + "Kwong" – adds a " "
s2 += s3; // s2 now equals "AliceKwong"
// why? s2+=s3; is the same as s2=s2+s3;
27EECS 1012 – York University
"1" + "2"
"1" + "2" - "3"
26
27
07/07/2021
14
string indexing [ ]
var str1 = "J. Trudeau";
0 1 2 3 4 5 6 7 8 9
J . T r u d e a u
index
character
we can think of a string as a sequence of characters. these characters can be
“indexed” starting from zero (0).
var first_letter= str1[0]; // assigns string "J" to first_letter
We can access an individual character in the string using an index [] notation.
The first character starts at index 0, not 1. This often confuses new programmers.
See next slide.
28EECS 1012 – York University
string indexing [ ]
var str1 = "J. Trudeau";
0 1 2 3 4 5 6 7 8 9
J . T r u d e a u
index
character
Expression Result
str1[0] "J"
str1[3] "T"
str1[2] " " (space character)
str1.length 10 (be careful – why 10?)
str1[str1.length-1] "u"
we can think of a string as a sequence of characters.
these characters can be “indexed” starting from zero (0).
29EECS 1012 – York University
28
29
07/07/2021
15
string + number types
• when the + operator is used between variables or expressions that are
string and numbers, the number type will be converted to a string.
• examples:
var str1 = "how many? ";
var strNum = "10";
var num = 10;
str1 = str1 + num; // result is "how many? 10".
strNum = num + strNum; // result is "1010"
strNum = "" + num; // result is "10"
this last example is a quick trick to convert any number type into a
string. "" is an empty string. Adding a number to an empty string
converts the number to a string.
31EECS 1012 – York University
How to get 20?
30
31
07/07/2021
16
a: 112
b: 32
a: 42
b: 106
arrays
21
What is an array?
var car = ["Saab", "Volvo", "BMW" ];
// We can access each individual value using the following notation.
// car[0]
// car[1]
// car[2]
is "Saab"
is "Volvo"
is "BMW"
this is similar to how we can access individual characters in a String
Type. Indexing starts from 0.
var len = car.length; // len is assigned 3
an array is a collection of variables that they all have the same
name, but their indices are different.
32
33
07/07/2021
17
array can store different types
var car = ["Saab", "Volvo", "BMW" ]; // Array of Strings
var nums = [ 1, 2, 3, 4, 5 ]; // Array of Numbers
var data = ["EECS1012", 780, "Su", 2021 ]; // Mix types
// data[0] is a string type with value "EECS1012"
// data[1] is a number type with value 780
34EECS 1012 – York University
Mixed type array not possible in C, C++, Java ..
control statements
• program flow control is the most powerful part of
programming
• it allows us to make decisions on whether to execute
some statements or not
• virtually all programming languages have some type of
control statements
▪ the most basic are :
• if statements (also called “branches”)
• for or while statements (also called “loops”)
35EECS 1012 – York University
34
35
07/07/2021
18
Booloean logic
• it is important to understand basic Boolean logic and
expressions
• Boolean logic concerns itself with expressions
that are “true” or “false”
• the name comes from the inventor,
George Boole
24EECS 1012 – York University
true/false expressions
Expression Meaning Boolean Result
45 < 10 is 45 less than 10? No. FALSE
45 < 100 is 45 less than 100? Yes. TRUE
50 > -1 is 50 greater than -1? Yes. TRUE
7 == 9 Is 7 equal to 9? No. FALSE
8 == 8 Is 8 equal to 8?Yes. TRUE
why the crazy double ==? In JS, a single = sign means assignment.
var a = 5. So, to distinguish the assignment =, from the comparison
if two items are equal, we use a ==.
37EECS 1012 – York University
36
37
07/07/2021
19
true/false example #2
Expression Meaning Boolean Result
var a = 5;
var b = 10;
a < b is 5 less than 10? yes. TRUE
a == b is 5 equal to 10? no. FALSE
a > b is 5 greater than 10? no FALSE
this becomes more interesting when we use variables.
38EECS 1012 – York University
equality with between types
Expression Meaning Boolean Result
var a = 5;
var b = “5”;
Assignment as Number
Assignment as String
a == b is 5 equal to“5”? In JS,yes! TRUE
a === b the triple-equal,tells JS to
consider the type in the equality
test. Is Number 5 equal to
String“5” ? no.
FALSE
39EECS 1012 – York University
38
39
07/07/2021
20
JS – comparison operators
Operator Description Comparing Returns
== equal to x == 8 false
x == 5 true
x == "5" true
=== equal value and equal
type
x === 5 true
x === "5" false
!= not equal x != 8 true
!== not equal value or not
equal type
x !== 5 false
x !== "5" true
x !== 8 true
> greater than x > 8 false
< less than x < 8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true
28
var x = 5;
Logical AND &&
• If both are T, the output is T; otherwise, the output is 0 (F)
“Weekend AND Sunny ➔ go hiking”
June 30th AND Afternoon ➔ test1
EECS1520: Logic Gates 41
Stay outside AND raining ➔ get wet
40
41
07/07/2021
21
Logical OR ||
• If both are F, the output is F; otherwise (either one of both
are 1 T, the output is T
EECS1520: Logic Gates 42
“stop request OR someone waiting ➔ pull over bus”
“Go inside OR use umbrella ➔ stay dry”
Email her OR Text her ➔ she gets notified
EECS1520: Logic Gates 43
42
43
07/07/2021
22
if statement
if (condition) {
statements;

} JS
if statements execute code within the { } if the
(condition) expression is true.
if the expression is false, the statements within
the { } are skipped.
condition
True
False
44EECS 1012 – York University
if statement example
if (grade == "A")
{
alert("I love EECS1012!");
}
JS
example
if the variable grade is equal to “A”, then the
statements are executed. Otherwise, the
statements within the { … } are skipped.
45EECS 1012 – York University
44
45
07/07/2021
23
if/else statement
if (condition) {
statements1;
} else {
statements2;
} JS
almost the same as the if statement, but in this
case, if the (condition) expression is false,
statements1 are skipped, but statements2 are
executed.
46EECS 1012 – York University
condition
True
False
if/else statement
if (grade == "A+" || grade == "A")
{
alert("I love EECS1012!");
}
else
{
alert("I hate EECS1012!");
} JS
Example
if the variable grade is equal to “A”, then the statements are executed.
Otherwise the statements within the else { … } are executed.
47EECS 1012 – York University
46
47
07/07/2021
24
while-loops
// while the condition is true
JS
var i=0;
var sum = 0;
while (i < 100) { // loop if i is less than 100 is true
sum = sum + i; // adds up 0 to 99
i++; // adds one to i
} JS
while (condition) {
statements;
}
Example
condition
True
False
48EECS 1012 – York University
computational thinking example
T
F
"sum = ", sum
sum  sum + i
sum 0
end
start
TASK
compute the sum
of numbers
between 10 and 30,
inclusively.
var sum = 0;
var i=10;
while (i <= 30) {
sum = sum + i;
i++;
}
alert("sum ="+sum);
JS
i ≤ 30
i  10
i i + 1
49Or < 31
48
49
07/07/2021
25
for (intitialization; condition; update) {
statements;
....
} JS
var
var
s1 =
s2 =
"hello";
""; // empty string
for (var
s2
i = 0; i
+= s1[i]
< s.length; i++) {
+ s1[i];
}
// s2 will equal "hheelllloo"
for-loop Falseinitialization
modification
True
condition
50
50
51
07/07/2021
26
computational thinking example
between 10 and 30, inclusively.
var sum=0;
for(var i=10; i<= 30; i++)
{
sum = sum + i;
}
alert("sum = "+sum);
JS
T
Fi 10
i i +1
i ≤ 30
“sum = ", sum
sum sum + i
sum 0
end
start
compute the sum of numbers
52Or < 31
for-loop more detail
for (initialization; condition; update) {
for_statements;
}
JS
update statement; //apply after for_statements
}
for-loop logic as a while loop
initialization statement;
while (condition expression)
{
for_statements;
for-loops are special cases
of while-loops.
53
52
53
07/07/2021
27
54
55
07/07/2021
28
JavaScript - functions
• a JavaScript function is a block of code that performs some
task
• a function is executed when something "calls"/ "invokes"
the function
56EECS 1012 – York University
function syntax
function name() {
statements;

}
function name(parameter1, parameter2, …) {
statements;

}
function name(parameter1, parameter2, …) {
statements;

return value;
}
keyword function is used to define a function.
name is the name of the function. The parenthesis
are used to denote it is a function that
accepts no parameters. See next slide.
this syntax allows parameters
to be "passed" to the function.
Parameter names are defined
between the (..) (see slide 71)
this syntax allows parameters
to be "passed" to the function.
note that the function also
returns a value.
1)
2)
3)
57EECS 1012 – York University
Return single piece of info.
If more, object, array
56
57
07/07/2021
29
function: Ex 1








function myFunction() {
alert("You clicked my function!");
}
example.js
simple function that calls an alert box with the text "You clicked my function!".
58EECS 1012 – York University
function name() {
statements;

}
function: Ex 2
41








function myFunction( num ) {
var words = ["zero", "one", "two"];
if (num < words.length)
{
alert(words[num]);
} else
{
alert("more than two");
}
}
example.js the parameter name is num.
num is a variable that takes the value
that was placed when the function
was called.
if the num is 2 or less, then print out
the word in the array. Otherwise,
print out "more than two".
This example combines many concepts.
Functions, parameters, arrays, and if-else
statements.
function name(parameter1, parameter2, …) {
statements;

}
58
59
07/07/2021
30
function: Ex 2.5






html
function doubleVar( p ) {
var result = p + p;
}
example.js
doubleVar() takes
a single parameter,named p. It
computes p+p and returns it.
alert( "Double " + result );
function: Ex 3








function doubleVar( p ) {
var result = p + p;
return result;
}
function func( num ) {
?
alert( "Double " + doubleValue );
}
example.js
the JS file define two functions.
The first,named doubleVar() takes
a single parameter,named p. It
computes p+p and returns it.
the second,named,myFunction(),
takes a parameter,named num. the
value in num is passed to the first
function. the returned result is
assigned to variable doubleValue.
this is displayed in an alert box.
function name(parameter1, parameter2, …)
{
statements;

return value;
}
60
61
07/07/2021
31
function: Ex 3








function doubleVar( p ) {
var result = p + p;
return result;
}
function func( num ) {
var doubleValue= doubleVar( num );
alert( "Double " + doubleValue );
}
example.js
the JS file define two functions.
The first,named doubleVar() takes
a single parameter,named p. It
computes p+p and returns it.
the second,named,myFunction(),
takes a parameter,named num. the
value in num is passed to the first
function. the returned result is
assigned to variable doubleValue.
this is displayed in an alert box.
function name(parameter1, parameter2, …)
{
statements;

return value;
}
objects
• number and string variables are containers for data
• objects are similar but can contain many values.
• objects also can associate functions (they are called methods
to distinguish them from the functions you just learned about).
• we will examine several pre-defined Objects in JavaScript
❑ Math
❑ Date
❑ document
63EECS 1012 – York University
62
63
07/07/2021
32
Math Object
/* PI is value associated with the Math object. We access it
using the "." operator, just like we did with length for
arrays and strings. num now equals 3.14159265358979 */
var num1 = Math.PI;
var num2 = -50.30;
var num3 = 4;
var num4 = 66.84
var result1 = Math.round(4.7);
var result2 = Math.abs( num2 ) ;
var result3 = Math.sqrt( num3 );
// method rounds a number
// method computes absolute value
// method computes the square root
var result4 = Math.min( num2, num3 ); // returns the minimum of a list of nums var
result5 = Math.max(num2, num3);
var result6 = Math.floor(num4);
var result7 = Math.ceil(num4);
// returns the maximum of list of nums
// rounds number down to nearest integer
// rounds up to nearest integer
more Match Object methods here: https://www.w3schools.com/js/js_math.asp
64EECS 1012 – York University
some Math methods
Function Description
Math.abs(n) absolute value
Math.ceil(n) ceil means round up to the nearest integer
9.01 would round up to 10.
Math.floor(n) floor means round down to the nearest integer
9.99 would round down to 9.
Math.min(n1, n2, ..),
Math.max(n1,n2,..)
min or max of a sequence of numbers:
e.g.max(50,43,1, -1,30) = 50
Math.sqrt(n) computes square root of n
Math.random() return a random number between 0 (included) and 1
(excluded). So, the number will be between 0 and
0.999999999…
Math.round(n) Traditional round approach,e.g.9.4999 would
round to 9; 9.50 would round up to 10.
65EECS 1012 – York University
properties: E, PI
64
65
07/07/2021
33
Math object
• random
▪ random is a Math object method that generates a
returns a random floating point number between 0
(inclusive) and 1 (exclusive) [ 0, 1)
// returns a number between 0 – 1. 0 is included, but not 1.
var num1 = Math.random(); // flip coin > 0.5 or not?
// returns a number between 0 – 5
var result = Math.floor(Math.random() * 6);
// returns a number between 0 - 99
var result = Math.floor(Math.random() * 100);
// returns a number between 0 - 100
var result = Math.floor(Math.random() * 101);
66EECS 1012 – York University
0 and 0.999999999…
66
67
07/07/2021
34
Date object
var day = myDate.getDay();
var year = myDate.getFullYear();
var month = myDate.getMonth();
var minute = myDate.getMinutes();
var second = myDate.getSeconds();
var dateStr = myDate.toDateString();
//returns day of the week
//returns the year
//returns the month
//returns the minute
//returns the seconds
//returns a string of the date
• Date object allows us to get information about the date.
• the format is different than the Math object. In this case, we
need to use the "new" keyword to create a new Date Ojbect
which is assigned to a variable.
var myDate = new Date();
68EECS 1012 – York University
Today: getDay(): 3
getMonth(): 6
Date methods
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (e.g. 2018)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
69EECS 1012 – York University
January is 0, February is 1,
and so on.
Today: getDay(): 3
getMonth(): 6
68
69
07/07/2021
35
document object
• the document object is another useful built-in object in
JavaScript.
• we have used the document object to change the text
inside a paragraph.
70EECS 1012 – York University
Changing HTML element
71
Attribute (CSS) Property or style object
color color: red; color style.color="red";
font-size fontSize
font-family fontFamily
text-align textAlign
background-color backgroundColor
border-top-width borderTopWidth
padding padding
display display
access/modify the properties of the DOM object
with objectName.propertyName
• innerHTML
• style
• checked t/f
• disabled t/f
• href
• src alt
• value
corrs to ele attributes
common properties
70
71
07/07/2021
36
example using document object
50






button not clicked





function myFunction() {
var p = document.getElementById("mydata");
p.innerHTML = "You clicked the button!";
}
JS file: example.js
Event click of the HTML button,
calls the specified handler function
51EECS 1012 – York University
PUTTING IT ALL TOGETHER
EXAMPLES
72
73
07/07/2021
37
HTML file










Button not clicked yet.




y>
74EECS 1012 – York University
example 2 – random number
function myFunction()
{
var num = Math.random(); // get a random number
var p = document.getElementById("mydata"); // get the paragraph
if (num < 0.5) // if num less than 0.5
{
p.innerHTML = num + " is less than 0.5 ";
}
else
{
p.innerHTML = num + " is equal to or large than 0.5";
}
}
75EECS 1012 – York University
74
75
07/07/2021
38
example 2 – output
before any click.
first click calls function.
HTML of paragraph is changed.
other clicks also calls function.
HTML of paragraph is changed.
76EECS 1012 – York University
example 3 – random greeting
var greetings = ["Hello", "Yo", "Hi", "Welcome"]; // declare array
var selectOne = myRandom(); // get random number between 0 -3
/* a function that returns a random number between 0 and 3 */
function myRandom() {
var num = Math.floor( Math.random() * 4 );
return num;
}
/* functioned called my our HTML page when the button is clicked */
function myFunction() {
var p = document.getElementById("mydata"); // get paragraph
p.innerHTML = greetings[ selectOne ]; // set paragraph
}
77EECS 1012 – York University
76
77
07/07/2021
39
example 3 – output
each click generates a new random
number and otuputs the corresponding
greeting in the array.
78EECS 1012 – York University
example 4 – for loops and string +
EECS1012 57
/* called when button is clicked. Passes a value from the HTML page */
function myFunction(num)
{
var sum = 0;
var outputString = "Adding 0"
var p = document.getElementById("mydata");
for(var i=1; i <= num; i++)
{
sum = sum + i;
outputString = outputString + "+" + i;
}
p.innerHTML = outputString + "= " + sum;
}

Button no clicked yet.



78
79
07/07/2021
40
comments on notation
in many programming languages, you will see the
following notations
xyz
text by itself is assumed to be a variable or object named xyz
“xyz"
text with quotes is assumed to be a string with content xyz
xyz()
text with parentheses after is assumed to be a function name xyz or
a method associatedwithan object.
58EECS 1012 – York University
Summary
variable, type
operators
Strings
Arrays
Control
Function
Object math,date, object
80
81
07/07/2021
41
Global vs local variables
Global variable is a variable that is created outside your function. Inside your function,
you do not need to declare it again. If you modify the variable, the modification will be
remembered next time you access the function.
var i = 1;
function myFunction() {
i += 1; // the value of i will be remembered next function call
} // can be used outside function, e.g., in another function
function myFunction2() {
i --;
}
function myFunction() {
var i = 1;
i += 1; // the value of i will not be remembered next function call
} // can not be used outside function, e.g., in another function
• No labs this Friday. Next lab posted later
this week
• Continue on your learning kits.
• SMQ3 this Saturday 13:00-23:59 (related to
today’s covered topic)
82
83


essay、essay代写