有两种类似于数组的数据结构在添加和删除元素时更为可控,它们就是栈和队列。

栈数据结构

栈是一种遵从后进先出(LIFO)原则的有序集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class stack {
constructor() {
this.items = [];
}
push(...elements) {
return this.items.push(...elements)
}
pop() {
return this.items.pop()
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return Boolean(this.items.length)
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
}

对于大量数据的使用使用一个对象来存储数据,查询效率更高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class stack {
constructor() {
this.count = 0;
this.items = {};
}
push(...elements) {
this.items[this.count] = elements;
this.count++;
}
pop() {
if (this.isEmpty()) {
return undefined;
}
this.count--;
const element = this.items[this.count]
delete this.items[this.count]
return element;
}
peek() {
if (isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
}
isEmpty() {
return this.count === 0;
}
clear() {
this.items = {};
this.count = 0;
}
size() {
return this.count + 1;
}
toString() {
if (this.isEmpty()) {
return '';
}
let objString = `${this.items[0]}`; // {1}
for (let i = 1; i < this.count; i++) { // {2}
objString = `${objString},${this.items[i]}`; // {3}
}
return objString;
}
}

私有属性/方法

新的提案通过#来声明私有属性

现阶段通过设置 Proxy 来禁止对类属性的访问

进制转换

十进制转二进制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function decimalToBinary(decNumber) {
const remStack = new Stack();
let number = decNumber;
let rem;
let binaryString = '';
while (number > 0) { // {1}
rem = Math.floor(number % 2); // {2}
remStack.push(rem); // {3}
number = Math.floor(number / 2); // {4}
}
while (!remStack.isEmpty()) { // {5}
binaryString += remStack.pop().toString();
}
return binaryString;
}

和其他任意的进制转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function convert(decNumber, base) {
const remStack = [];
const digs = '0123456789abcdefghijklmnopqrstuvwxyz'
let number = decNumber;
let rem;
let binaryString = '';
while (number > 0) {
rem = Math.floor(number % base);
remStack.push(rem);
number = Math.floor(number / base);
}
while (!remStack.isEmpty()) { // {5}
binaryString += digs[remStack.pop()];

return binaryString;
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信