没有 toString 等的关联数组
我想创建一个关联数组:
var aa = {} // Equivalent to Object(), new Object(), etc...
并且我想确保我访问的任何键都是数字:
aa['hey'] = 4.3;
aa['btar'] = 43.1;
我知道 JavaScript 没有打字功能,所以我无法自动检查这一点,但我可以确保在我的我自己的代码,我只将字符串分配给这个aa
。
现在我正在从用户那里获取密钥。 我想显示该键的值。 但是,如果用户给我类似“toString”的东西,用户会返回一个函数,而不是一个 int! 有没有办法确保用户给我的任何字符串都是我定义的?
唯一的解决方案是像下面这样吗?
delete aa['toString'];
delete aa['hasOwnProperty'];
ETC...
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;
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
.
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'];
etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能对您有用:
或者,我推荐这个通用解决方案:
请注意以下事项:键将在内部转换为字符串,因为键实际上是属性的名称。
如果尝试使用对象:
现在您知道它始终是一个字符串,让我们使用它:
This may work for you:
Alternatively, I recommend this generic solution:
Note the following: The key will internally be converted to a string because the key is actually a name of an attribute.
If trying to use an object:
Now that you know that it is always a string, let’s use it:
一种可能性是使用 hasOwnProperty 来检查键是否是您显式添加到数组中的内容。 因此,
您可以说:
或者,您可以使用 typeof 在返回之前检查任何内容是否为数字。 但我喜欢 hasOwnProperty 方法,因为它可以防止您返回任何您无意放入数组中的内容。
One possibility would be to use hasOwnProperty to check that the key is something you explicitly added to the array. So instead of:
you'd say:
Alternately, you could use typeof to check that anything is a number before returning it. But I like the hasOwnProperty approach, because it'll keep you from returning anything that you didn't intentionally put in the array.
当您创建新密钥时,请在其前面添加您自己的一些字符串常量:
When you create a new key, prepend it with some string constant of your own: