我想獲取一個空物件的變數名。我怎樣才能得到這個?
我的代碼
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
}
})
uj5u.com熱心網友回復:
無法從某個任意值獲取變數名稱。但是您可以自己提供元資訊。例如:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370121.html
標籤:javascript 数组 目的
上一篇:使用Javascript/Jquery將html屬性作為陣列讀取
下一篇:如何像陣列一樣選擇物件?
