javascript var assignment conversion to target type

Posted by pbhd on Stack Overflow See other posts from Stack Overflow or by pbhd
Published on 2013-10-19T20:43:20Z Indexed on 2013/10/19 21:55 UTC
Read the original article Hit count: 158

Filed under:

searching for a function, which converts rhs to the type of lhs. e.g.

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;

so such a function can be written, thats not the question. But: Is there somewhere a somehow complete implementation of such a thing? I started with something like that:

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);

which of course is not complete, but maybe shows what I'm goig for.

© Stack Overflow or respective owner

Related posts about JavaScript