我想獲取一個空對象的變量名。我怎樣才能得到這個?
我的代碼
var array = [foo, bar, baz]
array.map((el)=>{
if(Object.keys(el).length === 0) {
//give me name of var from an array which is empty
}
})
無法從某個任意值獲取變量名稱。但是您可以自己提供元信息。例如:
const foo = {a: 42};
const bar = {};
const baz = {b: 451};
// Use an object, instead of an array. With the following syntax
// the variable *creates* a property of the same name.
const configs = {foo, bar, baz};
// find *empty* elements:
const emptyConfigs = Object.entries(configs).reduce((acc, [k, cfg]) => {
return Object.keys(cfg).length === 0
? [...acc, k]
: acc;
}, []);
console.log(emptyConfigs);
參考:對像初始值設定項
或者,將信息包含在每個數組條目中。這有一個額外的好處,即配置可以/可以內聯(因此沒有名稱)。例如:
const foo = {a: 42};
const bar = {};
const baz = {b: 451};
const configs = [
{key: 'foo', cfg: foo},
{key: 'bar', cfg: bar},
{key: 'baz', cfg: baz},
{key: 'unnamed', cfg: {}}, // inlined config
];
const emptyConfigs = configs.reduce((acc, {key, cfg}) => {
return Object.keys(cfg).length === 0
? [...acc, key]
: acc;
}, []);
console.log(emptyConfigs);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句