在不存在的索引处插入数组 [英] Insert into array at non-existent index

查看:71
本文介绍了在不存在的索引处插入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从数据库中提取的数据在javascript中格式化数组,以便该行的ID是该数组的索引,因此该数据

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

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

看起来像

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

我尝试使用 array.splice( id,1,data),但是当我在console.log数组中索引不匹配时,几乎好像是因为索引不存在,才将值附加到数组末尾

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.

所以我想知道如何在任意索引处向数组添加数据,以便我可以创建一个如示例所示的数组

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";

这是因为JavaScript中的标准数组根本不是真正的数组,它们只是具有某些特殊行为的对象。数组条目只是对象属性。在JavaScript中,如果分配给尚不存在的对象属性,则会创建该属性。

This is because standard arrays in JavaScript aren't really arrays at all, they're just objects with some special behavior. Array "entries" are just object properties. And in JavaScript, if you assign to an object property that doesn't exist yet, it gets created.

如果计划使用数组,则只需要一个数组即可。功能,例如 length (在上面的示例中为 13 ;它总是比最高索引高一个,或者如果直接分配给 length splice 等,则为它给出的值。如果不要计划使用这些功能,您可以只使用一个对象( var a = {}; 而不是 var a = []; )。没有其他变化。

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 = [];). Nothing else above changes.

这篇关于在不存在的索引处插入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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