查找数组中元素的反向索引 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/30 15:08:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

