Angular

时间:2015-07-29 14:37:09

标签: javascript arrays angularjs

我正在使用Angular应用程序,其中我存储了与该信息的识别ID相关的一些信息。在角度应用程序中,我需要为单独的标识符提取信息并将其显示在屏幕上。

目前,我这样做:

var foo = [[]];

var info = {
    id: 950252,
    text: "Hello world."
};

foo[info.id] = info;

这允许我在AngularHTML中访问它,如下所示:

{{foo[id].text}} // Hello world.

这个问题是,数组将具有X个缺点,其中X是最高的识别值。这意味着仅在此示例中,有950,252个数组值存储为“null”。我觉得这是一种可怕的做法。

另一个想法是存储如下数据:

var foo = [];

var info = {
    id: 950252,
    text: "Hello world."
};

foo.push(info);

然而,通过这个实现,我不知道如何访问存储的id为950252的值,因为该位信息将位于数组中的随机索引(无论它是通过push插入的,是下一个可用的索引)但是我将无法通过foo[id]

知道该索引

1 个答案:

答案 0 :(得分:2)

使用对象文字而不是使用数组,否则最终会使用第一种方法创建稀疏数组(带有间隙的数组),而使用第二种方法,您已经注意到查找并不容易。使用这种方法而不是将id作为索引处理(在数组上),它将被视为键(在对象上)。

变化

var foo = [];

var foo = {};
//....
foo[info.id] = info;

如果你真的想要保留一个对象数组并且仍然想要维护一个单独的哈希,你可以通过创建另一个保存它的变量或者通过在数组对象本身上添加一个属性来实现,例如:

var foo = [];
foo.hash = {};
//
foo.hash[info.id] = (arr.push(info) - 1); //Store the hash as id and its current value as its current index. But remember to maintain it. Also use proper loop iteration mechanism to iterate through the array. If you are adding deleting items from array this is not a suitable approach as you would need to maintain the has indices as well.

//provided the id you can get the value as:
var infoSelected = foo[foo.hash[id]];

附注:您可能必须将此对象与作用域或控制器实例相关联,具体取决于您如何关联绑定。