曾經參加高德一道面試題,怎么把類似(175.46,37.876)坐標轉化為簡單的字符串來表示,當時還認為這是一道非常牛逼的題目,非常考察一個人的思維能力。回來的路上,想了一下,不就是考察了String的兩個方法嗎!fromCharCode和charCodeAt。
<script type="text/javascript">
function coordinateToStr(x,y){
x=x.toFixed(4);
y=y.toFixed(4);
x=x.toString().split(".");
y=y.toString().split(".");
return String.fromCharCode(x[0])+String.fromCharCode(x[1])+String.fromCharCode(y[0])+String.fromCharCode(y[1]);
}
function strToCoordinate(str){
var t=[];
t.push(str.charCodeAt(0));
t.push(str.charCodeAt(1));
t.push(str.charCodeAt(2));
t.push(str.charCodeAt(3));
return {
x:Number(t[0]+"."+t[1]),
y:Number(t[2]+"."+t[3])
}
}
var str=coordinateToStr(175.46,37.876);
console.log(str);
var coo=strToCoordinate(str);
console.log(coo);
</script>
