英文:
How to create a function to run an undefined amount of coordinates through a function to format them in JS
问题
我试图创建一个函数,通过一个未定义数量的坐标运行,先通过一个函数将它们标准化,然后用第二个函数格式化它们。这是第一个函数,用于标准化坐标(为其目的而工作):
function normalizeCoord(value) {
// 代码部分不需要翻译
}
这是我想用来运行未确定数量的坐标的函数(不起作用):
function formatCoords(...values) {
// 代码部分不需要翻译
}
console.log(
formatCoords(
normalizeCoord("42.9755,-77.4369", "[-62.1234, 42.9755]", "300,-9000")
)
);
我真的不确定我该怎么做。我尝试上面的方法,希望也许能取得一些进展(当然不是预期的结果,但我希望能得到标准化的坐标,然后进行格式化),但我只得到了第一组标准化的坐标(-77.4369, 42.9755),然后是"Uncaught Error: Invalid latitude at normalizeCoord"的错误。
英文:
I'm trying to create a function run an undefined amount of coordinates through a function that normalizes them, and then format them with the second function. This is the first function, to normalize the coordinates (Working for it's purpose):
function normalizeCoord(value) {
let noBrackets = value.replace(/[\[\]]+/g, "").replace(/ +/g, "");
let splitValue = noBrackets.split(",");
let lat1 = splitValue[0];
let long1 = splitValue[1];
let lat2 = splitValue[1];
let long2 = splitValue[0];
let result1 = `(${lat1}, ${long1})`;
let result2 = `(${lat2}, ${long2})`;
if (result1.charAt(0) === "-" || result2.charAt(0) === "-") {
result = result2;
} else {
result = result1;
}
let latInt1 = parseInt(lat1, 10);
let latInt2 = parseInt(lat2, 10);
let longInt1 = parseInt(long1, 10);
let longInt2 = parseInt(long2, 10);
if (latInt1 < -90 || latInt1 > 90 || latInt2 < -90 || latInt2 > 90) {
throw new Error("Invalid latitude");
}
if (longInt1 < -180 || longInt2 > 180 || longInt2 < -180 || longInt2 > 180) {
throw new Error("Invalid latitude");
}
return result;
This is the function that I want to use to run the undetermined amount of coordinates through (not working):
function formatCoords(...values) {
let coords = values;
for (var i = 0, n = coords.length; i < n; i++) {
normalizeCoord(coords);
}
return coords;
}
console.log(
formatCoords(
normalizeCoord(("42.9755,-77.4369", "[-62.1234, 42.9755]", "300,-9000"))
)
);
I'm honestly not sure on how I'm meant to go about this. I tried the above, expecting to maybe get somewhere (not the intended result of course, but of normalized coordinates that I could then format) but I only get back the first set of normalized coordinates (-77.4369, 42.9755), then the throw error of "Uncaught Error: Invalid latitude at normalizeCoord"
答案1
得分: 1
需要使用normalizeCoord
的返回值。目前,您进行了规范化,然后只是丢弃了结果。
另外,一次只传递单个坐标:
for (var i = 0, n = coords.length; i < n; i++) {
try {
const normalized = normalizeCoord(coords[i]);
coords[i] = normalized;
} catch (error) {
// 出错,不执行任何操作
}
}
英文:
You need to consume the return value from normalizeCoord
. Right now you do the normalization and then just throw away the result.
Also, pass just the single coords at a time:
for (var i = 0, n = coords.length; i < n; i++) {
try {
const normalized = normalizeCoord(coords[i]);
coords[i] = normalized;
} catch (error) {
// Error, do nothing
}
}
答案2
得分: 1
你需要使用 try.. catch。
function normalizeCoord( strVals ) {
const rgxfns = /[+-]?\d+(\.\d+)?/g; // 提取浮点数值
let
[v1,v2] = strVals.match(rgxfns).map(Number),
[lat,lon] = (v1 < 0 || v2 < 0) ? [v2,v1] : [v1,v2]; // .?
if (lat < -90 || lat > 90 ) throw new Error('Invalid latitude');
if (lon < -180 || lon > 180 ) throw new Error('Invalid longitude');
return `(${lat}, ${lon})`;
}
function formatCoords(...values) {
const coords = [];
values.forEach( val => {
try {
let coord = normalizeCoord( val );
coords.push({in:val, out: coord })
} catch (err) {
coords.push({in:val, out: err.message })
}
})
return coords;
}
console.log(
formatCoords( '42.9755,-77.4369', '[-62.1234, 42.9755]', '300,-9000' )
);
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
英文:
you need to use a try.. catch
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function normalizeCoord( strVals )
{
const rgxfns = /[+-]?\d+(\.\d+)?/g; // extract floats values
let
[v1,v2] = strVals.match(rgxfns).map(Number)
, [lat,lon] = (v1 < 0 || v2 < 0) ? [v2,v1] : [v1,v2] // .?
;
if (lat < -90 || lat > 90 ) throw new Error('Invalid latitude');
if (lon < -180 || lon > 180 ) throw new Error('Invalid longitude');
return `(${lat}, ${lon})`;
}
function formatCoords(...values)
{
const coords = []
;
values.forEach( val =>
{
try
{
let coord = normalizeCoord( val );
coords.push({in:val, out: coord })
}
catch (err)
{
coords.push({in:val, out: err.message })
}
})
return coords;
}
console.log(
formatCoords( '42.9755,-77.4369', '[-62.1234, 42.9755]', '300,-9000' )
);
<!-- language: lang-css -->
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论