gpt4 book ai didi

javascript - 确保使用范围内的参数调用库中的函数

转载 作者:行者123 更新时间:2023-11-30 21:12:07 26 4
gpt4 key购买 nike

我编写了一个接受对象作为参数的函数。所述对象包含各种附加参数。这与许多 jQuery 函数一样。

确保对象包含必需的最少参数的最佳方法是什么?如何为那些不需要的参数分配默认值?

这是我现在正在做的。

/*
var options = {
ListTitle: "",
WebPartID: "",
DisplayField: "Title",
EnforceUnique: true,
AllowEmpty: true,
RequireSelection: true,
NoSelectionMessage: "Please Select a Value",
ConnectedWebPartID: ""
}
*/

//Set Defaults.
dropdownFilterOptions.DisplayField = (typeof dropdownFilterOptions.DisplayField === "undefined" ? "Title" : dropdownFilterOptions.DisplayField);
dropdownFilterOptions.EnforceUnique = (typeof dropdownFilterOptions.EnforceUnique === "undefined" ? true : dropdownFilterOptions.EnforceUnique);
dropdownFilterOptions.AllowEmpty = (typeof dropdownFilterOptions.AllowEmpty === "undefined" ? true : dropdownFilterOptions.AllowEmpty);
dropdownFilterOptions.RequireSelection = (typeof dropdownFilterOptions.RequireSelection === "undefined" ? true : dropdownFilterOptions.RequireSelection);
dropdownFilterOptions.NoSelectionMessage = (typeof dropdownFilterOptions.NoSelectionMessage === "undefined" ? "Please select a value." : dropdownFilterOptions.NoSelectionMessage);

//Parameter Validation.
var parameterValidationSuccess = true;
if (typeof dropdownFilterOptions.ConnectedWebPartID === "undefined") {
throw "ConnectedWebPartID is required!";
parameterValidationSuccess = false;
}
if (typeof dropdownFilterOptions.ListTitle === "undefined") {
throw "ListTitle is required.";
parameterValidationSuccess = false;
}
if (typeof dropdownFilterOptions.WebPartID === "undefined") {
throw "WebPartID is required.";
parameterValidationSuccess = false;
}
if (!parameterValidationSuccess) return;

最佳答案

我想没有捷径可以检查所需的对象属性(必须一项一项地完成)。如果有人知道更好,请纠正我!

为了给不需要的参数赋值,Object.assign() 是一个不错的选择:

// parameterObject is passed into the function
// parameterObject === { prop1: "Peter", prop3: "yep", prop4: 500 }
var defaultObject = { prop1: "default value 1", prop2: "default value 2" };
var finalObject = Object.assign(defaultObject, parameterObject);
// finalObject === { prop1: "Peter", prop2: "default value 2", prop3: "yep", prop4: 500 }

在传递给函数的parameterObject 之上,被分配给defaultObject。这会覆盖所有可能从 parameterObject 中找到的 defaultObject 的属性,但不会影响仅属于 defaultObject 一部分的属性。

MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

关于javascript - 确保使用范围内的参数调用库中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026841/

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