将 "(5.035,1)"
格式的 PostgreSQL 点转换为 {x: 5.035, y: 1}
的最有效方法是什么?
我用PHP写的函数看起来像
function pointToArray($point) {
if ( strlen($point) == 0 ) return null;
$xy = explode(",", substr($point, 1, strlen($point)-2));
return array(
"x" => $xy[0],
"y" => $xy[1]
);
}
最佳答案
您可以在 Javascript 中使用与在 PHP 中相同的方法:
function pointToObject(point) {
if(!point.length) return null;
var split = point.slice(1, -1).split(",");
return {
x: +split[0],
y: +split[1]
};
}
我刚刚做的一个简单的基准测试能够在 1.53 秒内执行此函数 200 万次。
并且,为了更好的衡量,这里有一个从 NullUserException 中无耻地窃取的正则表达式解决方案,即 marginally faster在大多数浏览器上
function conv(s) {
var rx = /\(([^,]+),\s*([^)]+)\)/g;
var m = rx.exec(s);
return (!m ? null : { x: +m[1], y: +m[2]});
}
关于javascript - 字符串 (x,y) 到对象 {x, y},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12656232/