简体   繁体   English

在不存在的索引处插入数组

[英]Insert into array at non-existent index

I'm trying to format an array in javascript with data pulled from a database so that the ID of the row is the index of the array, so the data 我正在尝试使用从数据库中提取的数据在javascript中格式化数组,以便该行的ID是数组的索引,因此数据

ID | Data
----------------------------
1  | hi
2  | more data
4  | junk data
8  | hello world
12 | h3ll0

would look like 看起来像

array:
    [1] = hi
    [2] = more data
    [4] = junk data
    [9] = hello world
    [12] = h3ll0

i have tried using array.splice(id,1,data) but when i console.log the array the indexes don't match, almost as if because an index isn't exist before it just appends the value at the end of the array. 我已经尝试过使用array.splice(id,1,data)但是当我在console.log中索引不匹配的数组时,几乎就好像因为索引不存在之前它只是追加了值的结尾阵列。

So i am wondering how i can go about adding data to an array at any index so i can create an array as shown in the example 所以我想知道如何在任何索引处向数组添加数据,以便我可以创建一个数组,如示例所示

Believe it or not, you just assign to it: 信不信由你,你只需分配给它:

var a = []; // Creates array
a[1] = "hi";
a[2] = "more data";
a[4] = "junk data";
a[9] = "hello world";
a[12] = "h3ll0";

This is because standard arrays in JavaScript aren't really arrays at all , they're just objects with some special behavior. 这是因为JavaScript 中的标准数组根本不是数组 ,它们只是具有某些特殊行为的对象。 Array "entries" are just object properties. 数组“条目”只是对象属性。 And in JavaScript, if you assign to an object property that doesn't exist yet, it gets created. 在JavaScript中,如果您分配给尚不存在的对象属性,则会创建它。

You only need an array for this if you plan to use array features, like length (which will be 13 in the above example; it's always one higher than the highest index, or it's the value you give it if you assign to length directly), or splice , etc. If you don't plan to use those features, you can just use an object ( var a = {}; rather than var a = []; ). 如果你计划使用数组特征,你只需要一个数组,比如length (在上面的例子中它将是13 ;它总是比最高索引高一个,或者如果你直接指定length ,它就是你给它的值)或者splice等。如果您打算使用这些功能,您可以只使用一个对象( var a = {};而不是var a = []; )。 Nothing else above changes. 以上没有其他变化。

Don't use an array this way - if you have one element at index 9 then indicies 0-8 will then be 不要使用数组这种方式-如果你有索引一个元素的9然后indicies然后0-8 have values of 有价值的 undefined when you loop over it which can be very confusing, especially if you try to determine the length of your array. 当你遍历它时undefined ,这可能会非常混乱,特别是如果你试图确定数组的长度。

What you want to do be using, is an object with numeric keys. 您想要使用的是具有数字键的对象。

var x = {};
x.[id] = data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM