How to convert this function from as3 to javascript
I am a bit new to javascript so I am not sure how to re-write this function that's written in actionscript3 t开发者_JS百科o js:
function map(v:Number, a:Number, b:Number, x:Number = 0, y:Number = 1):Number {
return (v == a) ? x : (v - a) * (y - x) / (b - a) + x;
}
How would it look like in javascript? And what exactly are the reasons that this is not working right now?
It should work in JS if you take away all the type data, but you'll need to check for those default argument values because default arguments are not supported.
function map(v, a, b, x, y) {
if(x == undefined || isNaN(x)) x = 0;
if(y == undefined || isNaN(y)) y = 1;
return (v == a) ? x : (v - a) * (y - x) / (b - a) + x;
}
To specifically answer the last part of your question, there are two issues that prevent your code from running as JavaScript:
- JavaScript is a loosely typed language, and as such declaring types on function arguments is not permitted. To avoid surprising errors you could test every argument and throw an error it is not of the type you require.
- JavaScript does not allow for default arguments to be supplied, but does allow for function arguments to be omitted. This differs from ActionScript where not supplying an argument that has no default value will throw an error. The way to handle this is to test the arguments for being undefined, and setting values where required.
My additional test for NaN in the above is an extra precautionary layer and not required, but it could equally be used for all the arguments to make the code more robust.
Javascript does not have compile-time types. Remove all of the :Number
and you should be fine.
(Oops, missed the default parameter values, as noted in other answers)
function map(v,a,b,x,y){
if(x===undefined)x=0;
if(y===undefined)y=1;
return (v==a)?x:(v-a)*(y-x)/(b-a)+x;
}
精彩评论