Let's say you have a hash o
of arrays; for example registered callbacks for events, when each event can have 0 or more callbacks.
Is there a better way to say this in ES6?
if (key in o) o[key].push(x); else o[key] = [x]
By "better" I mean more easily understood by other developers. Possibly more concise, but not at the expense of readability. A particular (common) problem is that o
is often a longer expression, e.g. this.listeners
, and repeating it three times seems suboptimal. So real code might look like this:
if (event in this.listeners)
this.listeners[event].push(callback);
else
this.listeners[event] = [callback];
Sometimes you want to push single or multiple items in an array. So you can use the JavaScript push () method to add elements in an array. If you work with javascript arrays, you should read this javascript array posts: The javaScript push () method is used to add a new element to the end of an array.
Below are some of the different ways in which all elements of an array can be initialized to the same value: Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. This will initialize the num array with value 1 at all index.
If you work with javascript arrays, you should read this javascript array posts: The javaScript push () method is used to add a new element to the end of an array. Note: javaScript push () array method changes the length of the given array.
For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf () and if it doesn't then just push the item into the array: Show activity on this post. Show activity on this post.
By using the logical nullish assignment ??=
, you could check the property and if it is undefined
or null
, create a new array.
(o[key] ??= []).push(x);
Older approach:
You could use a logical OR and create an array if necessary.
o[key] = o[key] || [];
o[key].push(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With