简体   繁体   中英

Set associative array value in array

This seems quite simple, but I can't figure it out.

In PHP, I could do something like this:

$number_children[reference_number - 1][$key] = value;

In Javascript, I need to do the same: set a value in an associative array, which is in a normal array.

I've tried this:

number_children[reference_number - 1][key] = $(this).val();

This didn't seem to work. What's a simple method of setting this value?

Thanks for any help in advance.

Are you initializing the arrays?:

number_children = [];
number_children[reference_number - 1] = {};
number_children[reference_number - 1][key] = $(this).val();

Perhaps a jsFiddle would help show the problem.

In Javascript arrays and "associative arrays" are different. In fact, Javascript people don't use the term "associative arrays", they call them "objects" (or "hashes").

So, you can do this:

number_children[reference_number - 1] = {};
number_children[reference_number - 1][key] = $(this).val();

But this can have unexpected results when you try to iterate it, due to length not being set:

number_children[reference_number - 1] = [];
number_children[reference_number - 1][key] = $(this).val();

There is no such thing as associative array in JavaScript.

In PHP you have just arrays, which can be numerical, associative, or mixed. In JavaScript you have arrays or objects. Arrays in JavaScript are not associative.

Your code is perfectly fine if number_children is an array of objects. That means if this is array, which contains objects, which in turn have the property named as the value of key variable in your example.

tl;dr Post the actual problem code (with minimal required context) including any error message and/or [unexpected] symptoms.


As minitech has said: there is nothing "obviously" wrong with the code.

Anyway, I Just Learned (TM) that PHP has some form of auto-vivification . JavaScript has absolutely zero auto-vivification.

Thus,

$number_children[reference_number - 1][$key] = value;

Should work in PHP assuming that $number_children and $number_children[x] :

  1. Have not been set.
  2. Have previously been set to an "array".

Since JS does not work like this, then per SpoonNZ's or Sergio Tulentsev's answers, the object/array must be explicitly created before using the [] operator . (See their answers for an example).

Happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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