JavaScript: 无效的解构目标
JavaScript: Invalid destructuring target
代码如下:
function BinarySearchNode(key) {
let node = {};
node.key = key;
node.lft = null;
node.rgt = null;
node.log = () => {
console.log(node.key);
}
node.get_node_with_parent = (key) => {
let parent = null;
while (this) {
if (key == this.key) {
return [this, parent];
}
if (key < this.key) {
[this, parent] = [this.lft, this];
} else {
[this, parent] = [this.rgt, this];
}
}
return [null, parent];
}
return node;
}
我的 Firefox 是 44.0
,它为这些行抛出 SyntaxError
:
if (key < this.key) {
[this, parent] = [this.lft, this];
} else {
我试图通过阅读 this blogpost and the MDN 来理解这里到底出了什么问题。不幸的是,我仍然想念它:(
this
不是变量,而是关键字,不能赋值。改为使用变量:
node.get_node_with_parent = function(key) {
let parent = null;
let cur = this; // if you use an arrow function, you'll need `node` instead of `this`
while (cur) {
if (key == cur.key) {
return [cur, parent];
}
if (key < cur.key) {
[cur, parent] = [cur.lft, cur];
} else {
[cur, parent] = [cur.rgt, cur];
}
}
return [null, parent];
}
代码如下:
function BinarySearchNode(key) {
let node = {};
node.key = key;
node.lft = null;
node.rgt = null;
node.log = () => {
console.log(node.key);
}
node.get_node_with_parent = (key) => {
let parent = null;
while (this) {
if (key == this.key) {
return [this, parent];
}
if (key < this.key) {
[this, parent] = [this.lft, this];
} else {
[this, parent] = [this.rgt, this];
}
}
return [null, parent];
}
return node;
}
我的 Firefox 是 44.0
,它为这些行抛出 SyntaxError
:
if (key < this.key) {
[this, parent] = [this.lft, this];
} else {
我试图通过阅读 this blogpost and the MDN 来理解这里到底出了什么问题。不幸的是,我仍然想念它:(
this
不是变量,而是关键字,不能赋值。改为使用变量:
node.get_node_with_parent = function(key) {
let parent = null;
let cur = this; // if you use an arrow function, you'll need `node` instead of `this`
while (cur) {
if (key == cur.key) {
return [cur, parent];
}
if (key < cur.key) {
[cur, parent] = [cur.lft, cur];
} else {
[cur, parent] = [cur.rgt, cur];
}
}
return [null, parent];
}