gpt4 book ai didi

javascript - 如何为解构不存在的 key 抛出错误

转载 作者:行者123 更新时间:2023-11-29 17:45:41 24 4
gpt4 key购买 nike

所以我想解构一个对象并让它在其中一个键不存在时抛出错误。我尝试了 try catch 但它没有用。我想要一个替代方案,而不是 if (variable === undefined)

let obj = {test : "test"}

try {
let { test, asdf } = obj
console.log("worked")
}
catch (error) {
console.error(error)
}

最佳答案

使用proxy如果获取了不存在的属性则抛出错误

let obj = {
test: "test"
};

try
{
let { test, asdf} = getProxy(obj);
console.log("worked");
}
catch (error)
{
console.error(error)
}

function getProxy(obj) {
return new Proxy(obj, { //create new Proxy object
get: function(obj, prop) { //define get trap
if( prop in obj )
{
return obj[prop];
}
else
{
throw new Error("No such property exists"); //throw error if prop doesn't exists
}
}
});
}

演示

let obj = {
test: "test"
};

try
{
let { test, asdf} = getProxy(obj);
console.log("worked");
}
catch (error)
{
console.error(error)
}

function getProxy(obj) {
return new Proxy(obj, {
get: function(obj, prop) {
if( prop in obj )
{
return obj[prop];
}
else
{
throw new Error("No such property exists");
}
}
});
}

关于javascript - 如何为解构不存在的 key 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50021137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com