有没有办法像我们在 python 中访问列表那样访问减索引数组元素?

Moh*_*ABI 0 javascript string

var str=['a','c','d','o','p'];
Run Code Online (Sandbox Code Playgroud)

如何'o'使用像 str[-2] 这样的减号索引访问上面的字符串;在javascript中;

在 python 中,我很容易做到这一点,但我卡在这里了,请帮忙。

我正在为此任务工作。一个常见的现代用途是 ROT13 密码,其中字母的值移动了 13 位。因此'A'?'N','B' ?'O' 等等。

所以我想用减号访问。例如,如果给定的字母是 z,则索引是 25,所以我访问str[-str.length+13];

Sou*_*ani 5

好吧,没有办法做到这一点,但是您可以在 javascript 中为数组创建一个函数,然后您可以像下面这样:

str=["a", "c", "d", "o", "p"];

Array.prototype.accessViaIndex=function(index){
if(index<0){
   return this[(this.length+index)]
}
return this[index];
}

console.log(str.accessViaIndex(-1));
Run Code Online (Sandbox Code Playgroud)