【问题标题】:getting new nth indexed number of element from an array according to the given nth element in a circular manner根据给定的第n个元素以循环方式从数组中获取新的第n个索引元素
【发布时间】:2021-09-02 11:52:57
【问题描述】:

所以问题很简单。在这里,我想根据返回数组的新第 n 个元素 用户发送的前第 n 个元素。例如

['1','3','5','7','9','11']

如果用户发送值 3,那么我想返回 7,如果用户发送 5,那么我想返回 9,如果他们发送 7,那么我想返回 11,当他们发送 11 时,我想返回 3。基本上就像将数组置于循环模式并返回下一个元素。

这是我的代码。

var indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
var index=indices.indexOf(uservalue);            
return indices[index+index_to_add];

这里的一切都很好,但是当数组完成或接近结尾时,我会得到 undefined 而不是第一个元素。如果元素索引未定义或数组完成,我如何从头获取元素?

【问题讨论】:

  • 所以澄清一下:如果用户输入 3,你想获取匹配元素的索引,然后将 2 添加到该索引,并返回新索引指向的任何元素?
  • yes.... 如果索引不存在,则从头开始剩余索引

标签: javascript arrays indexing


【解决方案1】:

使用Modulo operator

return indices[(index+index_to_add) % indices.length];

注意:这只会处理uservalue 实际上是数组的一部分的情况。您可能想要添加类似if(index === -1) return 'Uservalue not in array.' 的子句或抛出错误。

【讨论】:

  • 谢谢。我花了一点时间才明白这一点,但它又短又甜。
【解决方案2】:

如果我正确解释了您的问题,解决方案是将处理封装在递归函数中,如果您正在使用可读代码并且不熟悉 Modulo 函数(这样做也更容易更改未来的进程):

const indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
console.log(GetElemAtIndex(GetIndex(userValue) + index_to_add));


function GetIndex(userValue) {
    return indices.indexOf(userValue); // If this is -1 the user has entered something not in the array
}

function GetElemAtIndex(toFind) {
    if (indices.length > toFind) {
        return indices[toFind];
    }
    else {
        return GetElemAtIndex(toFind - indices.toLength);
    }
}

Taxel 答案中的模函数是执行GetElemAtIndex 块的更有效方法。

【讨论】:

  • 谢谢。这实际上帮助我理解了 Taxel 的代码
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 2021-12-22
  • 2022-01-20
  • 1970-01-01
  • 2010-10-16
  • 2020-07-21
  • 2011-11-05
相关资源
最近更新 更多