Javascript 检查 JS 中是否设置了数组项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2613192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if an array item is set in JS
提问by Gusepo
I've got an array
我有一个数组
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
I tried
我试过
if (assoc_pagine[var] != "undefined") {
but it doesn't seem to work
但它似乎不起作用
I'm using jquery, I don't know if it can help
我在用jquery,不知道能不能帮上忙
Thanks
谢谢
回答by Stefan
Use the inkeyword to test if a attribute is defined in a object
使用in关键字来测试属性是否在对象中定义
if (assoc_var in assoc_pagine)
OR
或者
if ("home" in assoc_pagine)
There are quite a few issues here.
这里有很多问题。
Firstly, is varsupposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?
首先,var变量的值应该是“home”、“work”还是“about”?或者您的意思是检查名为“var”的实际财产?
If varis supposed to be a variable that has a string value, please note that varis a reserved word in JavaScript and you will need to use another name, such as assoc_var.
如果var应该是一个具有字符串值的变量,请注意它var是 JavaScript 中的保留字,您将需要使用另一个名称,例如assoc_var.
var assoc_var = "home";
assoc_pagine[assoc_var] // equals 0 in your example
If you meant to inspect the property called "var", then you simple need to put it inside of quotes.
如果您打算检查名为“var”的属性,那么您只需将其放在引号内。
assoc_pagine["var"]
Then, undefinedis not the same as "undefined". You will need typeofto get the string representation of the objects type.
然后,undefined与 不一样"undefined"。您将需要typeof获取对象类型的字符串表示形式。
This is a breakdown of all the steps.
这是所有步骤的细分。
var assoc_var = "home";
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // "number"
So to fix your problem
所以要解决你的问题
if (typeof assoc_pagine[assoc_var] != "undefined")
update:As other answers have indicated, using a arrayis not the best sollution for this problem. Consider using a Objectinstead.
更新:正如其他答案所表明的那样,使用数组不是解决此问题的最佳解决方案。考虑使用Object代替。
var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
回答by bobince
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
Don't use an Arrayfor this. Arrays are for numerically-indexed lists. Just use a plain Object({}).
不要Array为此使用 an 。数组用于数字索引列表。只需使用普通的Object( {})。
What you are thinking of with the 'undefined'string is probably this:
你想到的'undefined'字符串可能是这样的:
if (typeof assoc_pagine[key]!=='undefined')
This is (more or less) the same as saying
这(或多或少)与说相同
if (assoc_pagine[key]!==undefined)
However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefinedvalue for non-existent properties.
但是,无论哪种方式,这都有些难看。您正在取消引用一个可能不存在的键(这在任何更明智的语言中都是错误的),并依赖 JavaScript 的奇怪技巧为您undefined提供不存在的属性的特殊值。
This also doesn't quite tell you if the property really wasn'tthere, or if it was there but explicitly set to the undefinedvalue.
这也不能完全告诉您该属性是否真的不存在,或者它是否存在但明确设置为该undefined值。
This is a more explicit, readable and IMO all-round better approach:
这是一种更明确、可读和 IMO 全方位更好的方法:
if (key in assoc_pagine)
回答by xavierm02
var is a statement... so it's a reserved word... So just call it another way. And that's a better way of doing it (=== is better than ==)
var 是一个声明......所以它是一个保留字......所以只需另一种称呼它。这是一个更好的方法(=== 比 == 更好)
if(typeof array[name] !== 'undefined') {
alert("Has var");
} else {
alert("Doesn't have var");
}
回答by KooiInc
This is not an Array. Better declare it like this:
这不是数组。最好这样声明:
var assoc_pagine = {};
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
or
或者
var assoc_pagine = {
home:0,
about:1,
work:2
};
To check if an object contains some label you simply do something like this:
要检查对象是否包含某个标签,您只需执行以下操作:
if('work' in assoc_pagine){
// do your thing
};
回答by antonD
This worked for me
这对我有用
if (assoc_pagine[var] != undefined) {
instead this
取而代之的是这个
if (assoc_pagine[var] != "undefined") {
回答by Omn
TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)
TLDR;我能想到的最好的方法是:(根据您的用例,有多种方法可以优化此功能。)
function arrayIndexExists(array, index){
if ( typeof index !== 'number' && index === parseInt(index).toString()) {
index = parseInt(index);
} else {
return false;//to avoid checking typeof again
}
return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}
The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.
另一个答案的示例很接近,并且可以用于某些(可能是大多数)目的,但由于我在下面解释的原因,技术上非常不正确。
Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)
Javascript 数组仅使用“数字”键。当您在数组上设置“关联键”时,您实际上是在该数组对象上设置一个属性,而不是该数组的元素。例如,这意味着在使用 Array.forEach() 时不会迭代“关联键”,并且在计算 Array.length 时不会包括在内。(例外情况是像 '0' 这样的字符串将解析为数组的一个元素,但像 '0' 这样的字符串不会。)
Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.
此外,检查不存在的数组元素或对象属性确实评估为未定义,但这实际上并不能告诉您尚未设置数组元素或对象属性。例如, undefined 也是您通过调用不以 return 语句终止的函数而获得的结果。这可能会导致一些奇怪的错误和调试代码的困难。
This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);
这可能会令人困惑,但可以使用浏览器的 javascript 控制台轻松探索。(我用的是 chrome,每条注释都表示其前一行的评估值。);
var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"
This shows that associative keys are not used to access elements in the array, but for properties of the object.
这表明关联键不是用于访问数组中的元素,而是用于对象的属性。
foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3
This shows that checking typeof doesn't allow you to see if an element has been set.
这表明检查 typeof 不允许您查看是否已设置元素。
var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined
This shows the exception I mentioned above and why you can't just use parseInt();
这显示了我上面提到的异常以及为什么你不能只使用 parseInt();
If you want to use associative arrays, you are better off using simple objects as other answers have recommended.
如果您想使用关联数组,最好使用其他答案推荐的简单对象。
回答by Valeriu Vodnicear
if (assoc_pagine.indexOf('home') > -1) {
// we have home element in the assoc_pagine array
}
回答by Darlan Dieterich
回答by Hymanson Bicalho
function isset(key){
ret = false;
array_example.forEach(function(entry) {
if( entry == key ){
ret = true;
}
});
return ret;
}
alert( isset("key_search") );

