使用可视化面板的 JS 基础
Since my Algorithm Visualization Panel currently only supports JavaScript, I'll write an extremely simple JS tutorial to help you understand the basic usage of JS. The goal is to enable readers unfamiliar with JS to use the algorithm visualization panel.
With the advancement of AI tools, you generally don't need to write JS from scratch. AI tools can help translate code from other languages into JS. You just need to understand the basic syntax of JS and be able to read the code. So, if you are familiar with any other programming language, spending 5 minutes on the content below will enable you to use the visualization panel.
Basic JavaScript Syntax
Variable Declaration
First, let's talk about variable declaration in JavaScript. It has three ways to declare variables: var, let, const
.
const
is used to declare constants, which cannot be modified once declared. This is straightforward and is typically used in engineering code. Whether you use it in algorithm code is not critical.
const a = 1;
// error will be thrown
a = 2;
Both var
and let
can declare regular variables, but the visibility of the variables they declare is different. var
is more of a legacy issue. In general, you can consider their effects to be the same in the visual panel.
let str = "hello world";
str = "world"
// output world
console.log(str);
if (true) {
// the str here and the str outside are two different variables
let str = "hello";
// output hello
console.log(str);
}
However, you might notice that in my visualization code, the top-level functions are declared using var
, such as the solution code for the Fibonacci sequence:
This is because the JS function signatures provided by LeetCode use var
declarations, so I have followed the same practice. However, if you prefer to change it to let
, that's perfectly fine too. These are minor issues.
Function Declaration
JavaScript function declarations are also straightforward, like this:
function add(a, b) {
return a + b;
}
// output 3
console.log(add(1, 2));
The declaration of this function is the same as in other programming languages. However, in JavaScript, you might also see the following anonymous function declaration, which is essentially assigning an anonymous function to a variable. The usage is the same either way:
// replacing let with var will have the same effect
let add = function(a, b) {
return a + b;
}
// output 3
console.log(add(1, 2));
// declare using ES6 arrow function
let add = (a, b) => {
return a + b;
}
// output 3
console.log(add(1, 2));
Functions declared with the function
keyword and arrow functions declared with () => {}
have some key differences, mainly in how the this
pointer behaves within the function body. However, this feature is rarely used in algorithmic problems, so you can consider these two methods to be the same.
Loop Control
JavaScript's loop control is similar to other programming languages, with common loops being for
and while
.
Taking array traversal as an example, let's start with the most common method, using an index to traverse:
// traverse the array
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// output 1 2 3 4 5
然后是用 for...of
方式,可以直接遍历元素:
// Traverse the array
let arr = [1, 2, 3, 4, 5];
for (let item of arr) {
console.log(item);
}
// Output 1 2 3 4 5
Use `for ... of` to Iterate Elements
Note that JavaScript uses of
to iterate over array elements, not in
. in
has other uses, but we rarely need it for algorithm problems, so I won't elaborate.
I know some other languages use in
to iterate over array elements, so I want to remind you not to get confused.
The while
loop is the same as in other languages. Here's a simple example:
let arr = [1, 2, 3, 4, 5];
let i = 0;
while (i < arr.length) {
console.log(arr[i]);
i++;
}
// output 1 2 3 4 5
Conditional Statements
The usage of if else
is exactly the same as in other languages, so there's not much to say. Here's a simple example:
let a = 1;
if (a === 1) {
console.log("a equals 1");
} else {
console.log("a does not equal 1");
}
Use `===` for Equality Checks
There's a small pitfall here regarding the difference between ==
and ===
in JavaScript. ==
checks for value equality, while ===
checks for both value and type equality.
In simple terms, just remember that ==, !=
in other languages correspond to ===, !==
in JavaScript. Avoid using ==, !=
in JavaScript.
Basic Data Structures in JavaScript
Strings
Strings in JavaScript are similar to those in other languages, with no special differences. Here's an example:
let str = "hello world";
// output 11
console.log(str.length);
// output h
console.log(str[0]);
// output true
console.log(str === "hello world");
// split the string
let arr = str.split(" ");
// output ["hello", "world"]
console.log(arr);
// get a substring, multiple methods are available
// output hello
console.log(str.substring(0, 5));
// output hello
console.log(str.slice(0, 5));
// output hello
console.log(str.substr(0, 5));
// concatenate strings
let str2 = "world";
// output hello world world
console.log(str + " " + str2);
Arrays
There are several ways to create an array:
let arr1 = [1, 2, 3, 4, 5];
let arr2 = new Array(1, 2, 3, 4, 5);
// create an array of length 5, each element is undefined
let arr3 = new Array(5);
// create an array of length 5, each element is 0
let arr4 = new Array(5).fill(0);
Common Operations on Arrays:
let arr = [1, 2, 3, 4, 5];
// get the length of the array
// output 5
console.log(arr.length);
// get an element of the array
// output 1
console.log(arr[0]);
// modify an element of the array
arr[0] = 100;
// copy all elements of the array to a new array
let arr2 = arr.slice();
// this is also a method to copy an array
let arr3 = [...arr];
// add an element to the end of the array
arr.push(6);
// remove the last element from the array
arr.pop();
// add an element to the beginning of the array
// not commonly used, as algorithms generally avoid adding or removing elements from positions other than the end of the array
arr.unshift(0);
// remove the first element from the array
// not commonly used, as algorithms generally avoid adding or removing elements from positions other than the end of the array
arr.shift();
Alright, understanding the above basic operations is more than enough for you to use arrays in algorithm problems.
Hash Table
In simple terms, objects in JavaScript can be understood as hash tables because JavaScript objects consist of key-value pairs. However, with the introduction of the Map
type in ES6, we can be more formal and use the Map
type to create hash tables.
Basic operations of Map
:
let map = new Map();
// Add key-value pairs
map.set("a", 1);
map.set("b", 2);
map.set("c", 3);
// Retrieve key-value pairs
// Output 1
console.log(map.get("a"));
// Delete key-value pair
map.delete("a");
// Check if a key exists
// Output false
console.log(map.has("a"));
// Output true
console.log(map.has("b"));
// Iterate over key-value pairs
for (let key of map.keys()) {
console.log(key, map.get(key));
}
// Output b 2 and c 3
了解这些就差不多了,遇到不会处理的场景再查查文档就行了。
哈希集合
ES6 中引入的 Set
类型就是哈希集合,它用来存储不重复的元素,基本操作如下:
let set = new Set();
// Add elements
set.add(1);
set.add(2);
set.add(3);
// Delete an element
set.delete(1);
// Check if an element exists
// Output false
console.log(set.has(1));
// Output true
console.log(set.has(2));
// Traverse elements
for (let item of set) {
console.log(item);
}
// Output 2 and 3
Other Special Data Structures
In algorithm problems, you may also encounter special data structures such as linked lists, trees, binary heaps, etc. These data structures are not built-in to JavaScript. However, my algorithm visualization panel has implemented these special data structures. You can refer to my Introduction to the Algorithm Visualization Panel for specific usage.