I am using a function in a JavaScript framework where the return value can be ANY of the following
我在JavaScript框架中使用一个函数,其中返回值可以是以下任何一个
-
a single xy coordinate pair
一个xy坐标对
[x,y]
-
an array of xy coordinate pairs
一组xy坐标对
[[x,y],[x,y],...]
-
an array of arrays of xy coordinate pairs
xy坐标对的数组数组
[[[x,y],[x,y]],[[x,y],[x,y]],...]
The return value depends on the geometry of the object (single point, line, or multiple lines). Regardless of the return value and its array depth, I want to grab the first xy coordinate pair. What is an efficient way to do this?
返回值取决于对象的几何形状(单点,线或多行)。无论返回值及其数组深度如何,我都想获取第一个xy坐标对。有效的方法是什么?
Here is my code to achieve the objective so far:
这是我到目前为止实现目标的代码:
//here is the magic method that can return one of three things :)
var mysteryCoordinates = geometry.getCoordinates();
var firstCoord;
if(typeof mysteryCoordinates[0] === 'number') {
firstCoord = mysteryCoordinates;
} else if (typeof mysteryCoordinates[0][0] === 'number') {
firstCoord = mysteryCoordinates[0];
} else if (typeof mysteryCoordinates[0][0][0] === 'number') {
firstCoord = mysteryCoordinates[0][0];
}
I really hate this solution and am looking for something a bit more elegant.
我真的很讨厌这个解决方案,我正在寻找更优雅的东西。
2 个解决方案
#1
4
I guess in pure JS this should do it;
我想在纯JS中应该这样做;
var arr = [[[1,2],[1,3]],[[4,8],[3,9]]],
getFirstXY = a => Array.isArray(a[0]) ? getFirstXY(a[0]) : a;
console.log(getFirstXY(arr));
#2
2
A less efficient, but more elegant solution would be to use _.flatten
(http://underscorejs.org/#flatten):
效率较低但更优雅的解决方案是使用_.flatten(http://underscorejs.org/#flatten):
let firstCoord = _.flatten(mysteryCoordinates).slice(0, 2);
You could make it a little more efficient on average by slicing off the first two elements up-front as well:
你可以通过预先切掉前两个元素来使平均效率提高一些:
let firstCoord = _.flatten(mysteryCoordinates.slice(0, 2)).slice(0, 2);
console.log(_.flatten([1,2]).slice(0, 2));
console.log(_.flatten([[1,2],[1,3],[4,8],[3,9]]).slice(0, 2));
console.log(_.flatten([[[1,2],[1,3]],[[4,8],[3,9]]]).slice(0, 2));
<script src="http://underscorejs.org/underscore-min.js"></script>
#1
4
I guess in pure JS this should do it;
我想在纯JS中应该这样做;
var arr = [[[1,2],[1,3]],[[4,8],[3,9]]],
getFirstXY = a => Array.isArray(a[0]) ? getFirstXY(a[0]) : a;
console.log(getFirstXY(arr));
#2
2
A less efficient, but more elegant solution would be to use _.flatten
(http://underscorejs.org/#flatten):
效率较低但更优雅的解决方案是使用_.flatten(http://underscorejs.org/#flatten):
let firstCoord = _.flatten(mysteryCoordinates).slice(0, 2);
You could make it a little more efficient on average by slicing off the first two elements up-front as well:
你可以通过预先切掉前两个元素来使平均效率提高一些:
let firstCoord = _.flatten(mysteryCoordinates.slice(0, 2)).slice(0, 2);
console.log(_.flatten([1,2]).slice(0, 2));
console.log(_.flatten([[1,2],[1,3],[4,8],[3,9]]).slice(0, 2));
console.log(_.flatten([[[1,2],[1,3]],[[4,8],[3,9]]]).slice(0, 2));
<script src="http://underscorejs.org/underscore-min.js"></script>