有沒有辦法創建一個只回傳字串的函式?對于背景關系,我試圖創建附加為螢屏截圖的函式,目的是連接兩個字串并回傳另一個字串。但是,該函式也適用于數字,因為它添加了它們。在某些情況下,我只希望函式處理特定的資料型別。這可能嗎?
截圖在這里
function concatenate(a,b) {
return (a b);
}
uj5u.com熱心網友回復:
所以你要么將它們轉換成你想要的型別
function example (a, b) {
return a.toString() b.toString();
}
console.log(example("foo", "bar"));
console.log(example(1, 2));
或者您對型別進行驗證
function example (a, b) {
if (typeof a !== "string" || typeof b !== "string" ) {
throw new Error("Strings expected");
}
return a b;
}
console.log(example("foo", "bar"));
console.log(example(1, 2));
uj5u.com熱心網友回復:
可以創建接受型別的通用函式,并且它可以回傳進行所有可用于執行操作的驗證的函式。
function GenericConcat(typeA,typeB) {
return (a,b) => {
if (typeof a == typeA && typeof b == typeB ) {
return a b;
}
throw new Error("Parameter type expected: " typeA "-" typeB);
}
}
stringConcate = GenericConcat("string","string");
stringConcate("a","b"); //ab
stringConcate("a",1) //Error: Parameter type expected: string-string
numberConcate = GenericConcat("number","number");
numberConcate(1,2); //3
numberConcate("a",1); //Error: Parameter type expected: number-number
GenericConcat("string","string")("A","B");
GenericConcat("number","number")(1,2);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318474.html
標籤:javascript 功能
上一篇:如何讓函式在結束時執行任務?
