[英]Javascript string with arguments to single quotes
下面的調用函數依賴於雙引號和單引號,如何將其僅轉換為單引號並得到相同的結果?
const task.func = 'A'
const task.arg = 'B'
const callFunction = "doTask."+task.func+"('"+task.arg+"')"
console.log(callFunction); // doTask.A('B')
const callFunction = 'doTask.' + task.func + '(\'' + task.arg + '\')'
您需要使用\\
來轉義單引號\\
轉義單引號:
const task = { func: 'A', arg: 'B' }; const callFunction = 'doTask.' + task.func + '(\\'' + task.arg + '\\')'; console.log(callFunction); // doTask.A('B')
或者,如果您認為反引號是單引號,則可以使用模板文字 :
const task = { func: 'A', arg: 'B' }; const callFunction = `doTask.${task.func}('${task.arg}')`; console.log(callFunction); // doTask.A('B')
您不是在調用函數func
而是在創建一個字符串,該字符串看起來像下面一行中的function,
const callFunction = "doTask."+task.func+"('"+task.arg+"')";
另外,您無需使用引號,只需提供變量名稱作為參數即可。
嘗試這樣。
task = {}; task.func = function (arg){ return 'func called with arg : '+arg; }; task.arg = 'B'; const callFunction = 'doTask.'+task.func(task.arg); console.log(callFunction);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.