Copy link to clipboard
Copied
Is there any inbuilt method to get the index of a \n array by its value (in JSX). It seems that indexOf doesn't work here as in javascript..
FWIW, here's the implementation recommended by Mozilla (which has more robust error checking) :
...if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (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]);
Copy link to clipboard
Copied
nope!
i use this:
Array.prototype.findIndex = function (value)
{
var ctr = "";
for (var i = 0; i < this.length; i++)
{
// use === to check for Matches. ie., identical (===), ;
if (this == value)
{
return i;
}
}
return ctr;
};
don't know from who i got this snippet, but lots and lots of thanks
Copy link to clipboard
Copied
JSX is based on an older version of ECMAScript. indexOf did not used to exist for Arrays.
Here's an implementation that's equivalent to the javascript version:
Array.prototype.indexOf = function (elem, fromIndex){
fromIndex = fromIndex || 0;
for(var i = fromIndex; i < this.length; i++){
if(this == elem){
return i;
}
}
return -1;
}
There's a problem with Vamitul's version in that it returns a blank string if the index is not found, but it returns a number if it is. That makes it difficult to determine if the index is found or not. With the standard implementation you test for index < 0 to determine if the element is not found.
Harbs
Copy link to clipboard
Copied
Here's a more robust version which supports negative indices as well:
Array.prototype.indexOf = function (elem, fromIndex){
fromIndex = Number(fromIndex) || 0;
var len = this.length;
if (fromIndex < 0){
fromIndex += len;
}
for(var i=fromIndex;i<this.length;i++){
if(this == elem){
return i;
}
}
return -1;
}
Copy link to clipboard
Copied
FWIW, here's the implementation recommended by Mozilla (which has more robust error checking) :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (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 != Infinity && n != -Infinity) {
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
=== searchElement) { return k;
}
}
return -1;
}
}
Copy link to clipboard
Copied
thnx a lt for wonderful guide