搜索將rhs轉換爲lhs類型的函數。 例如javascript var分配轉換爲目標類型
var x=false // x is boolean now;
x=assign (x, "true"); //should convert "true" to boolean and return that
x=assign (x, 1); // dto, convert 1 to true
x=0 // x is number
x=assign (x, "123"); // should convert "123" to 123;
所以這樣的功能可以寫,那不是問題。但是:有沒有某種方式完全實現這樣的事情?我從這樣的事情開始:
function assign (v, x) {
if (typeof v==typeof x) {
return x;
}
switch (typeof v) {
case 'boolean' : {
return x=='true'?true:false;
}
case 'number' : {
return parseFloat(x);
}
}
return "xxx";
}
var v=true;
var x='true';
var r1=assign (v, x);
console.log (typeof r1+ " "+r1);
v=10;
x="123";
var r1=assign (v, x);
console.log (typeof r1+ " "+r1);
這當然是不完整的,但也許顯示我goig爲什麼。
你可能想看看[Typecast.js](http://www.typecastjs.org/)。 – DaoWen
@pbhd很難正確回答這個問題,因爲我們不知道你想要什麼。在JS中只有幾個基元,所以使用你的方法,你應該能夠創建一個自定義函數來滿足你需要的任何需求。 – plalx
對不起,我已經死了一個星期了......我只是在尋找一個保存lhs類型的函數(通過將它作爲arg傳遞,因此它具有typeinfo)。因此,如果lhs類型是數字,則強制指定返回一個數字,並且最好將傳遞的值(x)轉換爲數字。 – pbhd