问题描述
这是一个愚蠢的问题,那感觉就像之一。但是,心理障碍,现在是坏的。 (
我的问题是我有只由数字组成的数组。我想使用数组作为查找,但数字我通过查找数组中的一些继续寻找到数组中的一些在首页,不在于这个数字的存在阵列中的
例如:
VAR一个= [2,4,6,8,10]
B = 2;如果(一个并[b]){/ *如果数字2阵列的中存在,那么做一些*}
但是,着眼于在位置2数组的值( 6 ),不值2是否是数组中为止。这是非常合情合理的,但(心理障碍),我不能想出一个办法来测试数字......我还送一切字符串数组是否存在一个数字,但它确实强制类型转换和问题仍然存在。
拉我的头发在这里。请帮忙,谢谢。 :D
如果(a.indexOf(2)> = 0)
请注意,IE浏览器< 9没有的indexOf
,所以你会needto的情况下,添加它不存在:
如果(!Array.prototype.indexOf)
{
Array.prototype.indexOf =功能(searchElement / *,*的fromIndex /)
{
使用严格的; 如果(这===无效0 ||这个===空)
抛出新的TypeError(); 变种T =对象(this);
VAR LEN = t.length>>> 0;
如果(LEN === 0)
返回-1; 变种N = 0;
如果(的arguments.length大于0)
{
N =号码(参数[1]);
如果(N!== N)//快捷验证它是否为NaN
N = 0;
否则如果(正== 0&放大器;&放大器; N ==(1/0)及&放大器;!!n ==可 - (1/0))
N =(N大于0 || -1)* Math.floor(Math.abs(正));
} 如果(N> = LEN)
返回-1; VAR K = N'GT = 0
? ñ
:Math.max(LEN - Math.abs(n)时,0); 对于(; K< LEN; k ++)
{
如果(K在T&放大器;& T公司[K] === searchElement)
复位K;
}
返回-1;
};
}
This is a stupid question, it feels like one. But mental block is bad right now. :(
My problem is I have an array consisting only of numbers. I want to use that array as a lookup, but the number I pass to lookup a number in the array keeps looking to the array in the index of that number, not whether that number exists in the array.
For example:
var a = [2,4,6,8,10],
b = 2;
if(a[b]){ /* if the number 2 exists in the array a, then do something * }
But that looks at the array value in position 2 (6), not whether the value 2 is in the array. And this makes perfect sense, but (mental block) I can't figure out a way to test whether a number exists in an array of numbers... I even made everything strings, but it does type coercion and the problem persists.
Pulling my hair out here. Please help, thanks. :D
if (a.indexOf(2) >= 0)
Note that IE < 9 doesn't have indexOf
, so you'll needto add it in case it doesn't exist:
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;
};
}
这篇关于发现数字数组的项不使用环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!