我想知道是否有可能以比較一個int "1"
和一個字符串"!0"
,使結果真實。的Javascript評估字符串作爲一個比較操作
例如:
//Comparing 0 and "0" works...
var myVariable = 0;
var checkVariable = "0";
if(myVariable == checkVariable)
{
console.log('Works');
}
//Comparing 1 and "!0" doesn't work:
var myVariable = 1;
var checkVariable = "!0";
if(myVariable == checkVariable)
{
//I would LIKE this to be true!
console.log('This part doesn't work');
}
如何做到這一點任何想法?
我願意接受建議,並"!=0"
也將被罰款以及。
////////////////////////////////////////////// //// 更新:
所以我想現在的eval,和這裏的結果:
var myVariable = 20;
var checkVariable = "20";
eval(myVariable,checkVariable);
//Returns "20", which is ok I guess, but it would be nice if it returned "true"
var myVariable = 21;
var checkVariable = "!20";
eval(myVariable,checkVariable);
//Returns "21", which is ok, but it would be nice if it returned "true"
var myVariable = 21;
var checkVariable = "20";
eval(myVariable,checkVariable);
//Returns "20", which is *wrong*
在Chrome的JavaScript控制檯也試過這個(@Ishita):
var myVariable = 21;
var checkVariable = "!20";
myVariable == eval(checkVariable);
//Returns "false", which should be "true" :/
您必須使用您自己的解析器/解釋器或使用'eval()'來評估隱藏在字符串中的表達式。沒有辦法讓語言隱含。 – Pointy
http://en.wikipedia.org/wiki/Code_smell有一個更好的方法來處理這個問題 –
@CoryDanielson :(K我會想另一種方式。謝謝你們:) – Kayvar