gpt4 book ai didi

javascript - 解构函数参数时如何处理 "null"和 "undefined"值

转载 作者:行者123 更新时间:2023-11-30 07:49:28 24 4
gpt4 key购买 nike

function createElement (type, { attrs = {}, children = [] }) {
if (Object.prototype.toString.call(arguments[1]) !== '[object Object]') {
throw Error('The options argument must be an object');
}

return {
type,
attrs,
children
}
}

我有一个接受两个参数的函数:一个字符串和一个对象。在函数声明中,我通过解构解包对象的值。

当谈到确保第二个参数是一个对象时,我知道我可以做这个检查:Object.prototype.toString.call(arguments[1] !== 'object Object')

但是如果 nullundefined 作为参数传递,则会发生此错误:Uncaught TypeError: Cannot destructure property 'attrs' of 'undefined' or 'null '..这是可以理解的,因为不能将 nullundefined 强制转换为对象。我该怎么做才能防止这种情况发生?

如果 arraynumber 等作为第二个参数传递,则不会抛出错误,因为它们可以被强制转换,然后我可以在函数体中处理这些值.在处理nullundefined 时,函数中的代码永远不会执行。

// expected behaviour
createElement('div', []); // Uncaught Error: The options argument must be an object
createElement('div', function(){}); // Uncaught Error: The options argument must be an object
createElement('div', false); // Uncaught Error: The options argument must be an object
createElement('div', new Date()); // Uncaught Error: The options argument must be an object
createElement('div', 4); // Uncaught Error: The options argument must be an object

// unwanted behaviour
createElement('div', null); // Uncaught TypeError: Cannot destructure property `attrs` of 'undefined' or 'null'
createElement('div', undefined); // Uncaught TypeError: Cannot destructure property `attrs` of 'undefined' or 'null'

编辑以提供最终解决方案:阅读评论后,似乎唯一的解决方案是允许抛出异常或解构函数体中的代码并处理错误。这是我选择的解决方案:

createElement (type, opts) {
if (arguments[1] !== undefined && Object.prototype.toString.call(opts) !== '[object Object]') {
throw Error('The options argument must be an object');
}

const { attrs = {}, children = [] } = opts || {};

return {
type,
attrs,
children
}
}

最佳答案

使用默认值。

function createElement(type, { attrs, children } = {}) {
return {
type,
attrs,
children
}
}

console.log(createElement("foo"));
console.log(createElement("foo", undefined));

关于javascript - 解构函数参数时如何处理 "null"和 "undefined"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55638953/

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