我有一個功能
functionName(...arrayOfArguments, { test:"test }){}
有時我有arrayOfArguments,但有時只是null。我想讓這個函式動態化,所以如果arrayOfArguments有任何長度,它應該看起來像上面,但如果arrayOfArguments是 null,我不想傳遞它,只傳遞第二個引數,如:
functionName({ test:"test }){}
我怎樣才能使它成為動態的,所以如果它存在它將傳遞陣列,但如果它不存在則不會傳遞第一個引數?
如果我這樣做:
functionName(...arrayOfArguments, { test:"test }){}
并且arrayOfArguments是 null 它只會將 null 作為第一個引數傳遞。我如何定義這些論點?
uj5u.com熱心網友回復:
如果arrayofArguments是null,則不能在其上使用可迭代傳播;您必須使用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"]);
uj5u.com熱心網友回復:
需要兩個引數嗎?我認為您可以使用如下的物件引數來處理這種情況:
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 提到的 null(和/或未定義)應該可以解決問題。
uj5u.com熱心網友回復:
您可以公開一個接受陣列的公共函式,并在該函式內部宣告一個私有函式,該函式是具有邏輯的函式。
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; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/494311.html
標籤:javascript 数组 功能 目的
