2017-03-04 25 views
0

我試圖將if語句置於一個函數內,並且條件基於函數中使用的參數的名稱,而不是值。在JavaScript中檢查參數名稱,而不是值

什麼條件可以用來實現這一目標?可能嗎?如果沒有,是否有替代方案?

例如:

var lorem="The name is Lorem, but the value isn't."; 
var ipsum="The name is Ipsum, but the value isn't."; 
//the values shouldn't matter 

logIt(Lorem); 

function LogIt(theName){ 
    if(**the name of the variable theName = "lorem"**){ 
    console.log("The variable 'lorem' was used."); 
    }else if(**the name of the variable theName = "ipsome"**){ 
    console.log("The variable 'ipsum' was used."); 
    }else{ 
    console.log("huh?"); 
    } 
} 
+0

另外,你選擇將是永遠不要依賴傳遞的變量的名稱(誰是說那裏甚至有一個?)。這是非常不合邏輯的代碼。 –

+0

你想解決什麼具體問題? –

+0

我通過簡單地跟蹤迭代來解決它。謝謝! – kennsorr

回答

0

我相信這是不是真的可能得到在一般情況下,變量的名稱,因爲參數複製到函數參數。

也就是說,如果你只有一組固定的變量名和您正在使用ES6,你可以在技術上「黑客」與周圍物體解構的問題:

var lorem="The name is Lorem, but the value isn't."; 
var ipsum="The name is Ipsum, but the value isn't."; 

Logit({lorem}) 

function Logit({lorem, ipsum}) { 
    if(lorem) console.log("Function called with lorem"); 
    else if(ipsum) console.log("Function called with ipsum"); 
    else console.log("Function called with something else"); 
} 
+0

那麼你可能想看看這個答案它已經提到,這是可能的http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript。這裏使用的概念是動態變量。還有一些其他的方法。 – rresol

相關問題