检查数组项被JS设置 [英] Check if an array item is set in JS

查看:175
本文介绍了检查数组项被JS设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    var assoc_pagine = new Array();
    assoc_pagine["home"]=0;
    assoc_pagine["about"]=1;
    assoc_pagine["work"]=2;

我试过

    if (assoc_pagine[var] != "undefined") {

但它似乎并没有工作。

but it doesn't seem to work

我使用jQuery,我不知道这是否能帮助

I'm using jquery, I don't know if it can help

感谢

推荐答案

使用关键字测试如果一个属性在一个对象定义

Use the in keyword to test if a attribute is defined in a object

if (assoc_var in assoc_pagine)

if ("home" in assoc_pagine)


有相当多的问题在这里。


There are quite a few issues here.

首先,是 VAR 应该是一个变量的值是家,工作或关于?还是你的意思检查名为无功?

Firstly, is var supposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?

如果 VAR 应该是有一个字符串值的变量,请注意, VAR 是一个保留字在JavaScript中,你将需要使用其他名称,如 assoc_var

If var is supposed to be a variable that has a string value, please note that var is a reserved word in JavaScript and you will need to use another name, such as 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.

assoc_pagine["var"]

然后,未定义是不一样的未定义。您需要的typeof 来获取字符串重的对象类型的presentation。

Then, undefined is not the same as "undefined". You will need typeof to get the string representation of the objects type.

这是所有步骤的分解。

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") 


更新:至于其他的答案表明,使用的阵列是不是这个问题的最佳sollution。考虑使用对象代替。


update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.

var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;

这篇关于检查数组项被JS设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆