在JavaScript中从索引开始向后迭代数组

4

我有一段非常好的Python代码,但尝试将其移植到JavaScript上并不容易。

jsonLine = [[0,1],[2,4],[4,8],[9,12],[11,16],[12,13]]
[firstX, firstY] = [9,12]

if [firstX, firstY] in jsonLine:
    index = jsonLine.index([firstX, firstY])

    lineArray.append(jsonLine[index:])
    lineArray.append(jsonLine[index::-1])

jsonLine是由坐标组成的数组,用于表示一条线路,[firstX,firstY] 是用户定义的该线路上的起始点。我正在编写一个脚本,以该用户选择点为中心创建两条线路,分别朝着不同的方向延伸,稍后这些线路将被根据与用户点的距离进行切割。

在此情况下期望的输出结果为:

[[[9,12],[11,16],[12,13]],[[9,12],[4,8],[2,4],[0,1]]]

以下是我拥有的JavaScript代码,它可以获取所需数组中的第一个,但使用for循环感觉不太对,如果我使用jsonLine.reverse().slice(featureArray.length-vertex),似乎会复制推送到lineArray的数组。有没有更干净的方法来切片并反转数组?

for (var vertex = 0; vertex < featureArray.length; vertex++){
     if (jsonLine[vertex][0] === firstX && jsonLine[vertex][1] === firstY) {
        console.log(jsonLine.slice(vertex))
    }

for (var vertex = featureArray.length - cut; vertex--; ){ ... - adeneo
你可以使用 slice 函数创建第一个数组,然后使用 slice + reverse 函数创建第二个数组,类似于:[jsonLine.slice(vertex),jsonLine.slice(vertex).reverse()] - RobG
很遗憾,通过先切片,我只能得到我需要的两个数组中的第一个,但是是反向的,而不是第二个。我认为 lineArray = ([[featureArray.slice(vertex)],[featureArray.reverse().slice(featureArray.length - vertex)]]) 可以解决这个问题,谢谢。 - hansolo
啊,现在我明白你想要什么了:[[featureArray.slice(vertex)],[featureArray.slice(0,vertex + 1).reverse()]] - RobG
1个回答

2
您可以创建一个“find”方法,找到您感兴趣的坐标的索引。之后,应用“slice”和“reverse”以获得所需的格式:
var jsonLine = [
    [0, 1],
    [2, 4],
    [4, 8],
    [9, 12],
    [11, 16],
    [12, 13]
],
    el = [9, 12],
    index, res;

function findElement() {
    var i = 0;
    for (; i < jsonLine.length; i += 1) {
        if (jsonLine[i][0] === el[0] && jsonLine[i][1] === el[1]) {
            return i;
        }
    }
    return -1;
}
index = findElement();
res = [
    [jsonLine.slice(index)],
    [jsonLine.reverse().slice(index - 1)]// -1 because you want to repeat the element.
];
console.log(res);

Fiddle

注意:正如@RobG在本回答的评论中指出的那样,如果您想保持数组完整,请用jsonLine.slice(0, index + 1).reverse()代替第二部分。反转会修改原始数组,这可能是不希望发生的行为(尽管在问题中是否如此并不清楚)。


第二部分应该是 jsonLine.slice(0, index + 1).reverse(),否则 reverse 将修改原始数组。 - RobG
@RobG 谢谢,问题中没有明确说明那是否是后置条件。我默认它不是。无论如何,这是一个好观点。我在答案中引用了你并进行了更新。再次感谢。 - acontell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接