function lastIndexOf(O, searchElement, fromIndex) {
var len, n, k, kPresent, elementK;
// 1. Let O be the result of calling ToObject passing the this value as the argument.
// ninascholz: given as parameter
// 2. Let lenValue be the result of calling the [[Get]] internal method of O with the argument "length".
// ninascholz: given as parameter
// 3. Let len be ToUint32(lenValue).
len = O.length;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be ToInteger(fromIndex); else let n be len-1.
n = parseInt(fromIndex) || len - 1;
// 6. If n = 0, then let k be min(n, len – 1).
// ninascholz: should read n >= 0, otherwise the else condition would be wrong
if (n >= 0) {
k = Math.min(n, len - 1);
} else {
// 7. Else, n < 0
// a. Let k be len - abs(n).
k = len - Math.abs(n);
}
// 8. Repeat, while k= 0
while (k >= 0) {
// a. Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument ToString(k).
kPresent = k in O;
// b. If kPresent is true, then
if (kPresent) {
// i. Let elementK be the result of calling the [[Get]] internal method of O with the argument ToString(k).
elementK = O[k];
// ii. Let same be the result of applying the Strict Equality Comparison Algorithm to searchElement and elementK.
if (searchElement === elementK) {
// iii. If same is true, return k.
return k;
}
}
// c. Decrease k by 1.
k--;
}
// 9. Return -1.
return -1;
}
function out(s) { var n = document.createElement('div'); n.innerHTML = s + '<br>'; document.getElementById('out').appendChild(n); }
// 4. If len is 0, return -1.
out(lastIndexOf([], 'e', -2)); // -1
out([].lastIndexOf('e', -2)); // -1
// 6. If n = 0, then let k be min(n, len – 1).
out(lastIndexOf(['a', 'b', 'c', 'd', 'e'], 'c', 10)); // 4
out(['a', 'b', 'c', 'd', 'e'].lastIndexOf('c', 10)); // 4
// 7. Else, n < 0
out(lastIndexOf(['a', 'b', 'c', 'd', 'e'], 'e', -2)); // -1
out(['a', 'b', 'c', 'd', 'e'].lastIndexOf('e', -2)); // -1
out(lastIndexOf(['a', 'b', 'c', 'd', 'e'], 'e', -1)); // 4
out(['a', 'b', 'c', 'd', 'e'].lastIndexOf('e', -1)); // 4
// ii. Let same be the result of applying the Strict Equality Comparison Algorithm to searchElement and elementK.
out(lastIndexOf([0, 1, 2, 3, 4, 5], '5')); // -1
out([0, 1, 2, 3, 4, 5].lastIndexOf('5')); // -1
out(lastIndexOf(['a', 'b', 'c', 'd', 'e'], 'e', 2)); // -1
out(['a', 'b', 'c', 'd', 'e'].lastIndexOf('e', 2)); // -1
// iii. If same is true, return k.
out(lastIndexOf(['a', 'b', 'c', 'd', 'e'], 'e')); // 4
out(['a', 'b', 'c', 'd', 'e'].lastIndexOf('e')); // 4
<pre id="out"></pre>
Почему вы тег 'underscore.js'? – thefourtheye
это функция underscore.js –
http://underscorejs.org/#lastIndexOf –