寻找数组中元素的反向索引 - JavaScript
我们需要编写一个 JavaScript 函数,其中:第一个参数为字符串/数字文字数组,第二个参数为字符串/数字。
如果取第二个参数的变量不在数组中,则应返回 -1。
如果数组中存在该数字,则必须返回数字在数组反转后的位置的索引。必须做到这一点,而无需实际反转数组。
最后,我们必须将此函数附加到 Array.prototype 对象。
例如:
[45, 74, 34, 32, 23, 65].reversedIndexOf(23); Should return 1, because if the array were reversed, 23 will occupy the first index.
示例
代码如下:
const arr = [45, 74, 34, 32, 23, 65];
const num = 23;
const reversedIndexOf = function(num){
const { length } = this;
const ind = this.indexOf(num);
if(ind === -1){
return -1;
};
return length - ind - 1;
};
Array.prototype.reversedIndexOf = reversedIndexOf;
console.log(arr.reversedIndexOf(num));输出
这将在控制台中生成以下输出:
1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP