简体   繁体   English

Javascript-具有键值对的对象,其中value是一个数组

[英]Javascript - object with key value pair, where value is an array

I'm trying to create an object where there is a key value pair, and the value is an array. 我正在尝试创建一个具有键值对的对象,并且该值是一个数组。

ie: 即:

foo = {'key1':['val1','val2'], 'key2':['v3','v4']};

Is this possible in pure JS? 在纯JS中可能吗?

eg 例如

var foo = {};
foo['key1'] = ['keyOneVal1'];
foo['key1'] = ['keyOneVal2'];

but as you may have guessed, this just overwrites the keyOneVal1. 但是您可能已经猜到了,这只会覆盖keyOneVal1。

I've also tried 我也尝试过

var foo = {};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');

but couldn't get it working in a jsfiddle. 但无法在jsfiddle中运行。

EDIT: 编辑:

Okay heard you guys loud and clear. 好吧,听到你们大声而清晰的声音。 This object will not be initialized with an starting key, it's dynamically inserted based on time. 该对象将不会使用开始键进行初始化,而是根据时间动态插入的。 So in the end the object will look more like 所以最终该对象看起来更像

foo = {'time1':['a','b'], 'time2':['c','d','e','f'], 'time3':['y','y']};

It's very possible. 这很有可能。 Your second example is the correct way to do it. 您的第二个示例是正确的方法。 You're just missing the initializer: 您只是缺少初始化程序:

 var foo = {}; foo['key1'] = []; foo['key1'].push('k1v1'); foo['key1'].push('k1v2'); for(var i = 0; i < foo['key1'].length; i++) { document.write(foo['key1'][i] + '<br />'); } 

Try something like this make sure you declare key1: 尝试执行以下操作,确保您声明key1:

var foo = {"key1" : []};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');

It can be done like this 可以这样做

var foo = {"key":[]}
foo["key"].push("val1")
foo["key"].push("val2")

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

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