const canvas = document.querySelector('#draw');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
c.lineJoin = 'round';
c.lineCap = 'round';
c.lineWidth = 100;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
function draw(e) {
if (!isDrawing) return;
c.strokeStyle = `hsl(${hue}, 50%, 50%)`;
c.beginPath();
c.moveTo(lastX, lastY);
c.lineTo(e.offsetX, e.offsetY);
c.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
hue++;
}
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mousedown', (e) => {
[lastX, lastY] = [e.offsetX, e.offsetY];
isDrawing = true
});
canvas.addEventListener('mouseup', () => {isDrawing = false});
不会修改原数组!!
So:
Use if (arr.length) {}
class Node {
constructor(data) {
this.data = data;
this.children = [];
}
add(data) {
this.children.push(new Node(data))
}
remove(data) {
this.children = this.children.filter((child) => {
return child.data !== data;
})
}
}
class Tree {
constructor() {
this.root = null;
}
traverseBF(fn) {
const list = [this.root];
while (list.length) {
const node = list.shift();
list.push(...node.children);
fn(node);
}
}
traverseDF(fn) {
const list = [this.root];
while (list.length) {
const node = list.shift();
list.unshift(...node.children);
fn(node);
}
}
}
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
// insert 函数不需要 return 什么东西,可以直接回调
insert(data) {
if (this.left && data < this.data) {
this.left.insert(data);
} else if (data < this.data) {
this.left = (new Node(data));
}
if (this.right && data > this.data) {
this.right.insert(data);
} else if (data > this.data) {
this.right = (new Node(data));
}
}
// contain 函数需要 return. 所以回调中要一直 return
contains(data) {
if (data === this.data) {
return this;
} else if (this.left && data < this.data) {
return this.left.contains(data);
} else if (this.right && data > this.data) {
return this.right.contains(data);
} else {
return null;
}
}
}