尋找陣列中元素的反向索引 - 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
廣告