MIT Weblab笔记 - JavaScript Basis
Introduction
- Adding a Javascript file to HTML:
<script src="snake.js"></script>inside<head>section. - Any code that is not inside a function will run as soon as the script is loaded.
- Any functions that are called in the global code will be executed in the order they appear.
- When both files are included in the HTML with
<script>tags, they share the same global scope. This allows functions and variables defined in one file to be accessible in the other.
Run Javascript
node code.js
Triggering Javascript
Inline Event Handlers
<button onclick="buttonClicked()">Click Me</button>
function buttonClicked() {
alert("Button clicked!");
}
or
<button onclick="alert('Button clicked!')">Click Me</button>
The onclick attribute in the <button> tag specifies JavaScript code to run when the button is clicked.
Event Listeners
<button id="myButton">Click Me</button>
<script>
document.getElementById("myButton").addEventListener("click", function () {
alert("Button clicked!");
});
</script>
document.getElementById('myButton'): Selects the HTML element with the id myButton and returns a reference to the button element..addEventListener: Attaches an event handler to the selected element.
window.addEventListener("keydown", (event) => {
console.log(event.key);
});
window: The global window object represents the window containing the DOM document.
Page Load
<script>
window.onload = function () {
console.log("Page loaded!");
};
</script>
- The code inside
window.onloadruns when the entire page has finished loading.
Timers
setTimeout(function () {
alert("This alert appears after 3 seconds");
}, 3000);
setInterval(function () {
console.log("This message appears every 2 seconds");
}, 2000);
Syntax
Data Types
Primitive Types:
- boolean (true, false)
- number (12, 1.3, -45.6, 0)
- string (“Hello”)
- null
- undefined
Variables
var name = "John Doe";
let age = 30;
const isStudent = true;
- var: Declares a variable that can be globally or functionally scoped.
- let: Declares a block-scoped variable, which means it is limited to the
{}to which it is defined. - const: Declares a block-scoped variable that cannot be reassigned.
Operaters
===: Compares two values for equality without performing type conversion.==: Forcing the arguments to be of the same type before comparing them.
5 == "5"; // true
5 === "5"; // false
"hello" === "hello"; // true
=== can only compare primitive types! For objects, === compares references to them.
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
arr1 === arr2; // false
Arrays
let colors = ["red", "green", "blue"]; // initialize
console.log(colors[1]); // "green"
colors[2] = "white";
colors.pop(); // remove the last
colors.push("black"); // add to the back
colors.unshift("purple"); // add to the front
Conditional Statements
let time = 20;
if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
Loops
for (let i = 0; i < 5; i++) {
console.log("Number: " + i);
}
let i = 0;
while (i < 5) {
console.log("Number: " + i);
i++;
}
Objects
// Objects is key-value pairs inside a {}
let person = {
firstName: "Songlin",
lastName: "Zhao",
age: 30,
};
console.log(person.age); // 30
// object destructing: obtain multiple properties at once
const { firstName, lastName } = person;
console.log(firstName); // "Songlin"
console.log(lastName); // "Zhao"
// Array of objects
const snakeBody = [
{ x: 10, y: 11 },
{ x: 10, y: 12 },
{ x: 10, y: 13 },
];
Copying two objects
let arr = [1, 2, 3];
let copyArr = [...arr];
let obj = { name: "Eric" };
let copyObj = { ...obj };
Functions
const addOne = (num) => {
const result = num + 1;
return result;
};
console.log(addOne(4)); // Output: 5
- Function is unmodifiable, so use const functionName
- (parameters) => {function contents}
Class
class Person {
// Constructor method to initialize the object
constructor(name, age) {
this.name = name;
this.age = age;
}
displayDetails() {
console.log(`Name: ${this.name}, Age: ${this.age}`);
}
// Static method
static greet() {
console.log('Hello!');
}
}
const person1 = new Person('Alice', 30);
person1.displayDetails(); // Output: Name: Alice, Age: 30
Person.greet(); // Output: Hello!
Advanced
Callback Functions
Pass functions as parameters: Convert array of Celsius to Fahrenheit.
const modifyArray = (arr, func) => {
const newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(func(arr[i]));
}
return newArr;
};
const T2F = (tempC) => {
return (tempC * 9) / 5 + 32;
};
const tempsC = [0, 25, 100];
const tempsF1 = modifyArray(tempsC, T2F);
const tempsF2 = modifyArray(tempsC, (tempC) => (tempC * 9) / 5 + 32); // directly put the function in the parameter
- When using
{}, the return value should be specified by thereturnkeyword.
map()
const myArray = [1, 2, 3, 4, 5];
const newArray = myArray.map((num) => {
return num * 3;
}); // newArray = [3,6,9,12,15]
const newArray = myArray.map((num) => num * 3); // equivalent
- map() creates a new array.
- map() applies the callback function to every element of the array.
filter()
let values = [-1, -2, 3, 4, 5];
const filteredArray = values.filter(x => x > 0); // filteredArray = [3,4,5]
- filter() creates a new array.
- filter() selects the element which passes the “test”.
MIT Weblab笔记 - JavaScript Basis
http://example.com/2024/06/27/MIT_Weblab/javascript/