没有toString等的关联数组 [英] Associative array without toString, etc

查看:39
本文介绍了没有toString等的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个关联数组:

I want to create an associative array:

var aa = {} // Equivalent to Object(), new Object(), etc...

我想确保我访问的任何键都是数字:

And I want to be sure that any key I access is going to be a number:

aa['hey'] = 4.3;
aa['btar'] = 43.1;

我知道JavaScript没有类型,因此我无法自动检查它,但是我可以确保在自己的代码中仅将字符串分配给此aa.

I know JavaScript doesn't have typing, so I can't automatically check this, but I can ensure in my own code that I only assign strings to this aa.

现在,我正在从用户那里获取密钥.我想显示该键的值.但是,如果用户给我类似"toString"的信息,则用户将获得一个函数,而不是int!有没有办法确保用户给我的任何字符串只是我定义的内容?

Now I'm taking keys from the user. I want to display the value for that key. However, if the user gives me something like "toString", the user gets back a function, not an int! Is there a way to make sure any string the user gives me is only something I define?

是唯一的解决方案,如下所示吗?

Is the only solution something like the following?

delete aa['toString'];
delete aa['hasOwnProperty'];

等...

推荐答案

这可能对您有用:

function getValue(id){
  return (!isNaN(aa[id])) ? aa[id] : undefined;
}

或者,我推荐这种通用解决方案:

Alternatively, I recommend this generic solution:

function getValue(hash,key) {
    return Object.prototype.hasOwnProperty.call(hash,key) ? hash[key] : undefined;
}

请注意以下几点:该键将在内部转换为字符串,因为该键实际上是属性的名称.

Note the following: The key will internally be converted to a string because the key is actually a name of an attribute.

var test = {
  2: "Defined as numeric",
  "2": "Defined as string"
}

alert(test[2]); // Alerts "Defined as string"

如果尝试使用对象:

var test = {}, test2 = {};
test[test2] = "message"; // Using an object as a key.

alert(test[test2]); // Alerts "message". It looks like it works...

alert(test[test2.toString()]);
// If it really was an object this would not have worked,
// but it also alerts "message".

现在您知道它始终是字符串,让我们使用它:

Now that you know that it is always a string, let’s use it:

var test = {};

var test2 = {
    toString:function(){return "some_unique_value";}
    // Note that the attribute name (toString) don't need quotes.
}

test[test2] = "message";
alert(test["some_unique_value"]); // Alerts "message".

这篇关于没有toString等的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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