3

我有一个问题,或者更多一些奇怪的情况。我正在使用https://es6console.com

我想使用解构并将属性分配给已声明的变量。看来我声明对象的位置有问题。请打开https://es6console.com/jm6e72c7/并单击转换为 ES5。有一种奇怪的行为,我在变量之后声明对象。

// not working
let ip, port;

let config = {
    ip: 'ip',
    port: 'port'
}

({ip, port} = config)

console.log(ip);

//working
let obj = {
    name: 'name',
    age: 'age'
}

let name, age;

({name, age} = obj)

console.log(name);
4

3 回答 3

3

这是必须使用分号的情况之一:

let ip, port;

let config = {
	ip: 'ip',
	port: 'port'
};  //< --- you need the ;

({ip, port} = config)

console.log(ip);

否则 javascript 会将代码解释为:

let config = {ip: 'ip',port: 'port'}() which is a type error because it tries to call a function.
于 2018-09-17T14:53:51.773 回答
3

首先,它们都有效。将 ES6 代码编译为 ES5 有两种不同的方法:

({ip, port} = config)
// converted to
((_config = config, ip = _config.ip, port = _config.port, _config));

// and

({name, age} = obj)
// converted to
name = obj.name;
age = obj.age;

在这两种情况下,结果都是将变量设置为对象中的适当值。

不同之处在于转译器认为赋值操作的返回值在第一种情况下可能很重要,但在第二种情况下则不重要。所以在第一种情况下,你会_config在最后看到返回值。实际上,它不是必需的,但转译器是防御性的——它会尽最大努力确保功能完全相同

至于为什么config它认为您可能需要第一种情况下的返回值,是因为在声明对象后缺少分号。

添加分号后,它按预期工作:

let config = {
    ip: 'ip',
    port: 'port'
};

({ip, port} = config)

工作示例

于 2018-09-17T14:56:09.377 回答
0

问题是缺少分号。

let ip, port;

let config = {
	ip: 'ip',
	port: 'port'
}

({ip, port} = config)//this is being evaluated as part of the let config declaration...

console.log(ip);
console.log('------------------------------');

let obj = {
	name: 'name',
	age: 'age'
}

let name, age;

({name, age} = obj)

console.log(name);

需要是

let ip, port;

let config = {
	ip: 'ip',
	port: 'port'
};//added semicolon here

({ip, port} = config);//not needed here, but good to have

console.log(ip);
console.log('------------------------------');

let obj = {
	name: 'name',
	age: 'age'
}

let name, age;

({name, age} = obj)

console.log(name);

您会注意到,即使以 es6 运行,您也会在第一个代码段上遇到解构错误。这是因为口译员将声明解读为

let ip, port;
let config = {ip:'ip',port:'port'}({ip, port} = config)
于 2018-09-17T15:00:58.527 回答