Ecmascript next 动态对象属性javascript
javascript es6或es next是否有语法来实现以下行为Ecmascript next 动态对象属性javascript,ecmascript-next,ecmascript-2016,Ecmascript Next,Ecmascript 2016,javascript es6或es next是否有语法来实现以下行为 let t = { text: 'hello world', [shouldShow ? ...{'show' : 'test text'} : ''], test: 21 } 我想如果shouldShow是真的,那么对象t应该是真的 { text: 'hello world', show: 'test text', test: 21 } 如果shouldShow为false
let t = {
text: 'hello world',
[shouldShow ? ...{'show' : 'test text'} : ''],
test: 21
}
我想如果shouldShow是真的,那么对象t应该是真的
{
text: 'hello world',
show: 'test text',
test: 21
}
如果shouldShow为false,则对象t将为
{
text: 'hello world',
test: 21
}
我知道,我可以用if/else实现这一点,但我想问的是,是否有一种语法可以只用于一行代码 如果希望show属性在shouldShow为false时出现,请尝试以下操作:
// this would give show:"" when shouldShow is false, else it will give show="test text"
let shouldShow = false;
let t = {
text: "hello world",
show: shouldShow ? "test text" : "",
test: 21
};
如果您希望将其从对象本身中删除,请尝试此操作
// this would make show="test text" when shouldShow is true else remove it from "t"
let shouldShow = true;
let t = {
text: "hello world",
test: 21
};
t = shouldShow ? { ...t, show: "test text" } : t;
希望这能解决: 如果希望show属性在shouldShow为false时出现,请尝试以下操作:
// this would give show:"" when shouldShow is false, else it will give show="test text"
let shouldShow = false;
let t = {
text: "hello world",
show: shouldShow ? "test text" : "",
test: 21
};
如果您希望将其从对象本身中删除,请尝试此操作
// this would make show="test text" when shouldShow is true else remove it from "t"
let shouldShow = true;
let t = {
text: "hello world",
test: 21
};
t = shouldShow ? { ...t, show: "test text" } : t;