查找数组中元素的反向索引-JavaScript
我们需要编写一个JavaScript函数,该函数将String/Number文字数组作为第一个参数,并将String/Number作为第二个参数。
如果数组中不存在作为第二个参数的变量,则应返回-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