Shorthand 仅在定义变量时在对象中创建 属性 的方法

Shorthand Method to Create Property in Object only if Variable is defined

正在寻找一种 shorthand 方法来仅在定义分配变量时将属性分配给对象。

当前代码:

let count = {}, one = 1, two = 2, four = 4;
if (one) count.one = one; 
if (two) count.two = two; 
if (three) count.three = three; 
if (four) count.four = four; 

结果:
count = { 一:1,二:2,四:4 }

通常,我会尝试这个:

let count = { one, two, three, four }

但是,当 3 未定义时它会报错...

是否有更好的方法shorthand仅在定义时赋值?

我不能拥有的:

count = { 一:1,二:2,三:未定义,四:4 }

如果将可能未定义的项目放在特定对象上,可能会更容易。例如,这不会给你带来困难:

const stuff = {
    one: 1, 
    two: 2, 
    four: 4
}

let count = {
    one: stuff["one"],
    two: stuff["two"],
    three: stuff["three"],
    four: stuff["four"]
}

console.log(count)

您可以创建一个函数来检查变量是否未定义,如果此变量未定义,则不要将其添加到对象中。

var count = {}, one = 1, two = 2, four = 4;

function addToObject(value){
 if(typeof value === 'undefined') return
 this.count[value] = value;
}

this.addToObject(this.one);
this.addToObject(this.two);
this.addToObject(this.three);
this.addToObject(this.four);
this.addToObject(this.five);

console.log(this.count);
// {1: 1, 2: 2, 4: 4}

这仅在变量是全局变量并且可以被 window[name]
访问时有效 您需要一个包含您尝试获取的变量名的字符串列表

var target_list = ["one", "two", "three", "four"],
    count = {},
    one = 1, two = 2, four = 4;

for (let target of target_list) {
    if (window[target]) {
        count[target] = window[target];
    } else {
        console.log(`variable [${target}] not found`);
    }
}

console.log(count);

Getting All Variables In Scope

it complains when three is undefined...

不,它只会在变量 three 声明 时抱怨,而不是当它具有值 undefined 时。您可以轻松解决这个问题:

let one = 1, two = 2, three /* = 3 */, four = 4;

const count = JSON.stringify({one, two, three, four});
console.log(count);

如果变量没有在任何地方使用,你可以忽略它,因为它永远不会有任何价值。如果变量被使用(在某处赋值),你无论如何都需要在严格模式下声明它。