Javascript 不使用“解构”;未捕获引用错误:未定义道具“;
我试图找到一些关于解构的信息: 如果我这样做:Javascript 不使用“解构”;未捕获引用错误:未定义道具“;,javascript,destructuring,Javascript,Destructuring,我试图找到一些关于解构的信息: 如果我这样做: const { id, category: { categoryId } } = {}; 它抛出了一个错误 VM136:1 Uncaught TypeError: Cannot destructure property "categoryId" of "undefined" or "null". 因为我们试图访问category的propscategoryId,但category未定义 是否有任何解决方案可以只在一行解构中执行此操作?我试过:
const { id, category: { categoryId } } = {};
它抛出了一个错误
VM136:1 Uncaught TypeError: Cannot destructure property "categoryId" of "undefined" or "null".
因为我们试图访问category的propscategoryId
,但category未定义
是否有任何解决方案可以只在一行解构中执行此操作?我试过:
const{id,category:{categoryId=null}={}}={};
或
常量{id,类别:{categoryId}={categoryId=null}={};
但它不起作用。
我可以很容易地做到这一点:
const{id,category}={};
设categoryId=null;
if(category)({categoryId}=category);
谢谢大家!您的道具右侧必须有categoryId 或
const props = {id: 0, category: {categoryId: 0}} // your props have to look like this
const { id, category: { categoryId } } = props;
您必须在右侧有categoryId(在您的道具中) 或
const props = {id: 0, category: {categoryId: 0}} // your props have to look like this
const { id, category: { categoryId } } = props;
您可以拥有一个返回已破坏属性的iLife,并在其中添加对
category
的检查:
const obj={
id:5,
类别:空
};
常数{
身份证件
类别:{categoryId}
}=({id,category})=>({id,category:category |{}))(obj);
console.log(id,categoryId);
您可以拥有一个返回已破坏属性的生命,并在其中添加对类别的检查:
const obj={
id:5,
类别:空
};
常数{
身份证件
类别:{categoryId}
}=({id,category})=>({id,category:category |{}))(obj);
console.log(id,categoryId);
不幸的是,没有语法允许您选择解构。如果存在某些内容,您必须首先检查要解构的内容是否存在
有一个关于和的建议,但这在短期内对你没有帮助
同时,您可以查看哪些方法可以防止抛出所看到的错误,并且还允许您在不存在某些内容时提供默认值。不幸的是,没有语法允许您选择性地进行解构。如果存在某些内容,您必须先检查要解构的内容是否存在
有一个关于和的建议,但这在短期内对你没有帮助
同时,您可以查看哪些方法可以防止抛出您看到的错误,并且还允许您在不存在某些内容时提供默认值。是的,您可以使用默认值
var{id,category:{categoryId}={categoryId:'some'}}={}
console.log(categoryId)
//将categoryId的默认值设置为时,它将始终获得该默认值
//如果未定义Destructured值
var{id,category:{categoryId=null}={}}={};
console.log(categoryId)
是您可以使用默认值
var{id,category:{categoryId}={categoryId:'some'}}={}
console.log(categoryId)
//将categoryId的默认值设置为时,它将始终获得该默认值
//如果未定义Destructured值
var{id,category:{categoryId=null}={}}={};
console.log(categoryId)
如果类别未定义,则无法获取categoryId
const{id,category:{categoryId}}={category:{categoryId:1};
console.log(categoryId)
如果类别未定义,则无法获取categoryId
const{id,category:{categoryId}}={category:{categoryId:1};
console.log(categoryId)
const{id,category:{categoryId}={};
是错误的。你不能从空对象中解构任何东西。你实际上试图从中解构信息的对象是什么样子的?@Andy我相信问题是,如果你试图解构的部分或全部属性在被解构的对象中不存在,你如何避免抛出错误。const{id,category:{categoryId=null}={}};
这句话是正确的,可以用,但是你在这里使用了两个默认值,所以categoryId
将以null
结束,你想在categoryId中有什么值?我只是不想在尝试访问categoryId时出错,它可以是null或'{},我不在乎,这不是我的项目,这是一个简单的例子来做一些更复杂的事情。只是为了提高我在JS=Dconst{id,category:{categoryId}={};
是错误的。你不能从空对象中解构任何东西。你实际上试图从中解构信息的对象是什么样子的?@Andy我相信问题是,如果你试图解构的部分或全部属性在被解构的对象中不存在,你如何避免抛出错误。const{id,category:{categoryId=null}={}};
这句话是正确的,可以用,但是你在这里使用了两个默认值,所以categoryId
将以null
结束,你想在categoryId中有什么值?我只是不想在尝试访问categoryId时出错,它可以是null或'{},我不在乎,这不是我的项目,这是一个简单的例子来做一些更复杂的事情。只是为了提高我在JS=D中的技能