javascript数组数字键会导致多余的“未定义" [英] javascript array numerical key resulting in excess "undefined"

查看:112
本文介绍了javascript数组数字键会导致多余的“未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于当前webApp的OOD系统,该系统的每个元素都有一个ID,并放置在每个页面的elements数组中.每个新元素的id都是连续数字,而与放置elemenet的页面无关,因此,例如,如果在一个项目中有7个页面,那么我们有25个元素,则无论新元素的ID放置在哪一页26岁 因此,例如,其中包含2个元素(ID为1和4)的项目的第一页将是:

I have an OOD system for my current webApp that every element has an id and is placed in the elements array of each page. the id of each new element is a continuous number regardless of the page that the elemenet is placed at, so for example if we have 25 elements in a project that has 7 pages, the ID of the new element no matter which page it's placed will be 26. So for example page one of a project that has 2 elements in it with IDs of 1 and 4 will be :

[undefined, proto.constructor, undefined, undefined, proto.constructor ]

这样对元素进行修饰非常容易,因为我需要的只是元素的页码和ID,并且我可以调用该元素,例如pages [1] .elements [1].但是我使用此方法的问题在于,它导致最终JSON中过多的未定义"元素,从而使JSON不必要地变得太大.有什么办法解决吗?

this way refrencing an element would be very easy because all I need is the page number and ID of the element and I can call the element, for example pages[1].elements[1]. But the problem that I have with this method is that it results in excessive number of "undefined" elements in the final JSON which makes the JSON too big unnecessarily. Is there any way around that ?

推荐答案

使用JS对象而不是数组.它仍然可以具有看似数字的键(它们实际上是字符串,但是对于数组也是如此),并且具有相同的恒定时间查找优点.

Use a JS object instead of an array. It can still have numeric-looking keys (they're actually strings, but that's true for arrays, too) and has the same constant-time lookup benefits.

所以,而不是像这样的代码……

So, instead of code like this…

var objectsById = [];
objects[object.id] = object;

…而是像这样编写代码:

…instead write code like so:

var objectsById = {};
objects[object.id] = object;

JSON输出将很简洁(尽管不一定要排序):

The JSON output will be terse (though not necessarily sorted):

{ "42":"someserializablevalue", "17":"another JSON value" };

这篇关于javascript数组数字键会导致多余的“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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