有效的语法用于填充一个javascript关联数组 [英] Efficient syntax for populating a javascript associative array

查看:153
本文介绍了有效的语法用于填充一个javascript关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动完成的文本框,用户可以输入一个项目code到,需要找出该项目code的ID号是在JavaScript。

这是关联数组是我想象的方式,它应该做的事,但下面似乎有点长篇大论,我希望有人有更好的办法做到这一点还是我下面的简写:

  VAR itemIds =新的Array();
itemIds [ITEM1] = 15;
itemIds [ITEM2] = 40;
itemIds [项目3] = 72;
...功能getItemId(code){
    返回itemIds [code];
}


解决方案

你在做什么不是一个数组 - 它是一个对象(在JavaScript对象是在PHP关联数组的等效ISH)

您可以使用JavaScript对象文字语法:

  VAR itemIds = {
    ITEM1:15,
    ITEM2:40,
    项目3:72
};

JavaScript对象的成员可通过点符号或数组下标,像这样访问:

  itemIds.item1;
itemIds ['ITEM1'];

您需要使用第二个选项,如果你有成员名称作为一个字符串。

I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.

An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:

var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...

function getItemId(code){
    return itemIds[code];
}

解决方案

What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).

You can use JavaScript object literal syntax:

var itemIds = {
    item1: 15,
    item2: 40,
    item3: 72
};

JavaScript object members can be accessed via dot notation or array subscript, like so:

itemIds.item1;
itemIds['item1'];

You'll need to use the second option if you've got the member name as a string.

这篇关于有效的语法用于填充一个javascript关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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