在此期间,我决定深入研究TypeScript,并开始通过实现一些基本数据结构来实践它。我正在尝试实现使用自定义节点的自定义堆栈。
我的StackNodes定义如下:
class StackNode {
private val: any;
private nxt: StackNode | undefined = undefined;
constructor(val: any, nxt?: StackNode | undefined) {
this.val = val;
this.nxt = nxt || undefined;
}
get value(): any {
return this.value;
}
get next(): StackNode | undefined {
return this.next;
}
}
export default StackNode;
和实际堆栈:
class Stack {
private capacity!: number;
private top?: StackNode | undefined = undefined;
private size: number = 0;
constructor(capacity: number, initialValues?: Array<any>) {
this.capacity = capacity;
if (initialValues) {
this.size = initialValues.length;
this.top = this._initStack(initialValues, initialValues.length - 1);
}
};
private _initStack = (array: Array<any>, idx: number): StackNode => {
if (idx == 0) {
return new StackNode(array[idx], undefined);
} else {
return new StackNode(array[idx], this._initStack(array, idx-1));
}
}
pop(): any {
const value = this.top?.value();
this.top = this.top?.next();
return value;
}
}
export default Stack;
这里的问题是在弹出方法this.top = this.top?.next()
中使用可选链接运算符的行>
我了解的是,表达式this.top?.next()
应等效于
(this.top === null || this.top === undefined)? undefined : this.top.next()
但我仍然收到错误
无法调用可能是'undefined'的对象。ts(2722)
即使在那个阶段不应该取消定义,但仍进行了呼叫时。
为什么?我在这里想念什么? StackNode.nxt和Stack.top均允许未定义。我已经尝试过以这种旧方式进行此操作:
if (this.top !== null || this.top !== undefined) { const value = this.top.value() this.top = this.top.next() }
但是我仍然会遇到相同的错误,即使在此应确保不能不确定
this.top
的定义,但必须是(或至少应该是)StackNode类型。
这应该如何工作,当从空堆栈弹出时,pop方法将返回未定义的值,而当弹出最后一个元素时,其下一个未定义的元素将被设置为堆栈的顶部。
我正在使用TS 3.8.3
在此期间,我决定深入研究TypeScript,并开始通过实现一些基本数据结构来实践它。我正在尝试实现使用自定义节点的自定义堆栈。我的...
您将next定义为吸气剂,因此必须按如下方式对其进行访问:this.top = this.top?.next