For the contents below, I will summarize A memo of javascript for you.
Syntax
这部分主要介绍代码逻辑上的处理,在第二部分将会重点介绍如何与HTML交互。
Basic Syntax
Quite similar with C++ and Python syntax! Just skip that part.
variables & const variables
1
let user_name = "not_entered_yet"
string methods
1 2 3 4 5 6 7 8 9
// string methods let username = "hello world" const string_value = document.getElementById("string-method") string_value.textContent = `The first letter: ${username.charAt(3)}`
let text = window.prompt("Input your string") text = text.trim().charAt(0).toUpperCase() + text.trim().slice(1).toLowerCase() console.log(text)
Functions
Arrow functions: Just a syntactic sugar, like the lambda expressions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// variables with scopes functiontest1(x) { console.log(`Input x value is ${x}`) x++; let y = 100 console.log(`Now the x value in this function is ${x}`) }
let x = 10 test1(x) console.log(`Now the x outside the function is ${x}`)
Callbacks are functions passed as arguments to other functions to be executed later (usually after an asynchronous operation completes). They’re essential in JS because: JavaScript is single-threaded, so callbacks allow non-blocking handling of tasks like:
// call back & not call back consthello = () => setTimeout(function() { console.log("Hello without callback");}, 3000); constgoodbye = () => console.log("Goodbye without callback");
functiongoodbye_with_callback() { console.log("Goodbye with callback") }
console.log("This is the function without using callback:") hello() goodbye()
console.log("This is the function using callback:") hello_with_callback(goodbye_with_callback)
In the console, you will see something like this:
1 2 3 4 5 6
This is the function without using callback: Goodbye without callback This is the function using callback: Hello without callback Hello with callback Goodbye with callback
With callback, “Hello” is ensured to be executed before “Goodbye”.
We can view everything as variables, like the “function pointer” in Cpp and “callable” in Python, functions in js can also be seen as variables!
Arrays in js
There are many powerful operations to deal with arrays in js.
// arrays in js let numbers = [1, 2, 3, 4, 5] console.log(numbers)
// ... to unpack all the value in array console.log(...numbers)
// e.g.1 find the max value in an array let max_value = Math.max(...numbers) console.log(max_value)
// e.g.2 usage of spread operators let original_username = "Hello world" let new_username = [...original_username].join("-") console.log(original_username) console.log(new_username)
// rest parameters: receive multiple parameters in function as an array // !kwargs in Python receive multiple parameters as an dictionary (like json file!) functionprint_number(...numbers) { console.log(numbers) console.log(...numbers) } print_number(1, 2, 3, 4, 5)
A very important method in combining arrays and functions in js!
Advanced methods for arrays
forEach(callbackfn)
map(callbackfn)
reduce(callbackfn)
filter(callbackfn)
The design of callbackfn in the parameters is to design a function which will accept the value, index and array accordingly and iterate with all the values in the array.
// advanced usage with array functionecho_number(value, index, array) { console.log(`The value of this is ${value}`) console.log(`The index is ${index}`) console.log(`The whole array is ${array}`) return value }
let number = []; for (let i = 1; i <= 10; i++) { number.push(i); }
//* 1 forEach method: no return value value = number.forEach(echo_number) // no return value, it will return undefined console.log(value)
// * 2 pow method: return an array console.log(number.map(pow))
// .filter using a predicate for boolean return value, return an array console.log(number.filter(is_odd))
// .reduce // 4 parameters: previous value(for recursion), current value, current index and array // !previous value is the return value for the previous element as the parameter functionsum(previous_value, current_value, current_index, array) { console.log(`Previous value is ${previous_value}`) console.log(`current value is ${current_value}`) console.log(`current index is ${current_index}`) console.log(`The whole array ${array}`) return current_value + previous_value } const sum_all = number.reduce(sum) console.log(sum_all)
OOP in js
For struct(onject), the same as Cpp.
1 2 3 4 5 6 7 8 9
// OOP in javascripts: like struct in Cpp person_1 = { firstname: "hello word", lastname: "wow", is_male: true, final_answer: this.lastname, };
console.log(person_1.firstname)
You can use constructors below to create a new object!
// modified to be a class in ES6 classStudent_n { static school = "sjtu" constructor(name, gender, id, grades) { this.name = name; this.gender = gender; this.id = id; this.grades = grades; }
// !gettlers and settlers, for grabage value processing this private value setgrades(new_grades){ if (new_grades < 105){ // private property this._grades = new_grades; }else{ console.log(`Grades is too high!`) } }
getgrades(){ returnthis._grades; }
// several methods in OOP display_student() { console.log(`This is a student!`);
if (this.gender == `male`) { console.log(`He is a boy`); } elseif (this.gender == `female`) { console.log(`She is a girl`); } else { console.log(`Emmm, something strange.`) }
functionRollDice() { const dice_num = document.getElementById("dice-num").value; let value_array = []; for (let i = 0; i < dice_num; i++) { // generate random number from 0 to 6 let random_number = Math.floor(Math.random() * 6) + 1 // console.log(random_number) value_array.push(random_number) }
console.log(value_array)
// output on the screen const dice_result = document.getElementById("dice-result"); dice_result.textContent = value_array.join(",") }
Importing Modules
You can importing modules from external js files:
First, modify your html files:
1
<scripttype="module"src="index.js"></script>
Use export for exporting functions and variables.
1 2 3
exportfunctiontestfun(){ console.log(`Hello, this is a module`); }
// !closure in javascripts // message is private, which cannot be accessed outside the variable scope, while the inner function has the accessment! functionouter() { let message = "hello" functioninner() { console.log(message); }
inner(); } outer();
// closure for state maintenence functioncreate_counter(){ let count = 0; functioninner_increment(){ count ++; console.log(count); }