get the number of the reverse order of a given series
I want to get the number of the reverse order of a given series in javascript. If I have the following series:
[1,2,2,2,5,5,7,8,8,10]
then if the input is number 8
the output should be 2
, since:
1 = 10
2 = 7
2 = 7
2 = 7
5 = 5
5 = 5
7 = 4
[8 = 2]
[8 = 2]
10 = 1
//--> [1 , 2,3,4, 5,6, 7, 8,9, 10]
--> [1 , 2,2,2, 5,5, 7, 8,8, 10]
[10, 7,7,7, 5,5, 4, 2,2, 1 ] <-- // ==> [1,2,2,4,5,5,7,7,7,10]
Here is what I have done so far:
function getReverseNumber(arr, num)
{
var newArr = new Array(arr.length);
var temp;
var counter = 1;
for(var i = arr.length; i > 0; i--)
{
if(temp === arr[i])
{
newArr[arr.length - i] = counter;
continue;
}
newArr[arr.length - i] = counte开发者_如何学Gor;
temp = arr[i];
counter++;
}
return newArr[num - 1];
}
but it doesn't work as expected:
getReverseNumber(new Array(1,2,2,2,5,5,7,8,8,10), 8) // returns 5 not 2
what is wrong in my function?
I think that you are overcomplicating it. You are only increasing counter
by one when you increase it, and you place the numbers in revese order, so newArr
end up as [1,2,2,3,4,4,5,5,5,6]
instead of [10,7,7,7,5,5,4,2,2,1]
.
There is no need to calculate all those numbers and keep in an array. Just loop from 1 and up, and calculate which position that is in the array. Return the index when you find the value:
function getReverseNumber(arr, num) {
for (var i = 1; i <= arr.length; i++) {
if (arr[arr.length - i] == num) return i;
}
return -1; // not found
}
Demo: http://jsfiddle.net/Xedz6/
Works in IE6 even ;)
function getReverseNumber(arr,num){
alert(arr[ arr.length + arr.indexOf(num) * -1 ]);
}
getReverseNumber(new Array(1,2,2,2,5,5,7,8,8,10), 8); // alerts 2
Working demo: http://jsfiddle.net/AlienWebguy/7qvzE/
fiddle tested in IE 8 and 7 enjoy
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
...
arr[ Math.Abs(arr.indexOf(num)-arr.length-1)]
sorry about the formatting. I'm on my phone.
check out lastIndexOf
a = [1,2,2,2,5,5,7,8,8,10]
n = a.lastIndexOf(8)
alert(a.length - n)
Regarding these "IE8" remarks - even if dealing with obsolete browsers, this is not an excuse for reinventing the wheel. Use standard documented javascript library functions and include compatibility/degradation layers when appropriate.
精彩评论