函数,第一个参数是可选的和动态的



我有一个函数

functionName(...arrayOfArguments, { test:"test }){}

有时我有arrayOfArguments,但有时它只是null。我想让这个函数是动态的,所以如果arrayOfArguments有任何长度,它应该像上面一样,但如果arrayOfArguments为null,我不想传递它,只传递第二个参数,比如:

functionName({ test:"test }){}

我如何使它成为动态的,这样它会在数组存在的情况下传递数组,但如果不存在,就不会传递第一个参数?

如果我只是这样做:

functionName(...arrayOfArguments, { test:"test }){}

并且CCD_ 5为null,则它将在那里传递null作为第一个参数。我该如何定义这些论点?

如果arrayofArgumentsnull,则不能对其使用可迭代排列;为了避免出现错误,您必须使用arrayOfArguments ?? []进行呼叫。这将导致该数组的参数被传递给functionName(后面是具有test属性的对象)。

因此,这意味着一种选择是,函数应该期望零个或多个参数,然后是末尾带有test属性参数的对象。您可以定义functionName来支持这一点,方法是将其所有参数收集到一个数组中,然后将对象从数组末尾弹出:

function functionName(...theArray) {
const obj = theArray.pop();
console.log(`theArray has ${theArray.length} elements; obj.test = ${obj.test}`);
}
function example(arrayOfArguments) {
functionName(...arrayOfArguments ?? [], { test:"test" });
}
example(null);
example([]);
example(["a"]);
example(["a", "b"]);

另一个选项是将对象从末尾移动到开头。您仍然需要?? [],但它使功能更简单:

function functionName(obj, ...theArray) {
console.log(`theArray has ${theArray.length} elements; obj.test = ${obj.test}`);
}
function example(arrayOfArguments) {
functionName({ test:"test" }, ...arrayOfArguments ?? []);
}
example(null);
example([]);
example(["a"]);
example(["a", "b"]);

最后,您可以直接将arrayOfArguments传递到函数中,而不是将其展开:

function functionName(theArray, obj) {
console.log(`theArray ${theArray ? `has ${theArray.length} elements` : "is null"}; obj.test = ${obj.test}`);
}
function example(arrayOfArguments) {
functionName(arrayOfArguments, { test:"test" });
}
example(null);
example([]);
example(["a"]);
example(["a", "b"]);

是否需要两个参数?我认为您可以使用如下对象参数来处理这种情况:

const functionName = ({ arrayOfArguments, testParam }) => {
if (arrayOfArguments != undefined && arrayOfArguments != null) {
// code if arrayOfArguments is defined and not null
} else {
// code if arrayOfArguments is either undefined or null
}
console.log('arrayOfArguments', arrayOfArguments);
console.log('testParam', testParam);
};
functionName({ testParam: { "test": "test" } });
functionName({ arrayOfArguments: null, testParam: { "test": "test" } });
functionName({ arrayOfArguments: ['a', 'b'], testParam: { "test": "test" } });

如果处理单个对象参数不符合您的要求,那么评估空(和/或未定义)arrayOfArguments(如上面提到的@deceze)就可以了。

您可以公开一个接受数组的公共函数,在该函数内部,您可以声明一个私有函数,该函数就是具有逻辑的函数。

function publicFn(array) {
const privateFn = (obj, nestedArray) => console.log(`array with ${nestedArray.length} elements and the obj.test === ${obj.test}`);
privateFn({ test: "test" }, array || []);
}
publicFn();
publicFn(null);
publicFn([]);
publicFn(["a"]);
publicFn(["b"]);
publicFn(["a", "b"]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新