How to assign a series of variables with similar name - javascript

I declared six variables:
let L1, L2, L3, R1, R2, R3
and then I want to assign these six variables with the same value:
L1 = "something";
L2 = "something";
L3 = "something";
R1 = "something";
R2 = "something";
R3 = "something";
There must be a shorter way to do this right? I want to do it in a loop, because in this example we only have six variables, but in fact I have a lot of them.

The main way I see you being able to accomplish this is using an object (as others have already pointed out). You will still need to instantiate all the variables initially using the long-form syntax; but then you will be able to use a "for in" loop to actually assign all of the necessary values:
let something = {
L1: null,
L2: null,
L3: null,
};
for (let prop in something){
something[prop] = 1;
};
console.log(something);
Hope this helps!

I will directly answer your question, even though I think you shouldn't do that, you should think in a more "javascript" way of doing this.
That said:
const value = "something";
const numberOfVars = 100;
for( let i=0; i< numberOfVars; i++)
eval( "L"+ i + " = value" );
That would create the variables L0 to L99 with the value "something" inside. You could do that for any name, be it R, L or any string which is a valid javascript variable name.

Why not use an object instead?
const bubbles = {
bubbleL1,
bubbleL2,
bubbleL3,
bubbleR1,
bubbleR2,
bubbleR3
};
If you want to use array methods on it, you can extract an array of the values from the object with Object.values.
For your new question, you can fill an array with values, then destructure:
const [L1, L2, L3, R1, R2, R3] = new Array(6).fill('something');
console.log(L1);
console.log(R3);

If you want to give each variable its own name, but also have them grouped together so that you can use a blanket statement to set all their values, you got two easy options:
Option 1:
Use an array. An array will not allow you to name your variables, but they will be auto-assigned "names" according to their position (index) in the array. For example, if you made an array of the following values: "Cookie", "Money", and "Nothing." then they would be assigned numbers to reference them by, "Cookie" would be named "0", "Money" would be named "1", "Nothing." will be named "2" and so on... Here's an example of what an array looks like:
var nameOfArray = ["value1","value2","value3"];
and to access the value of an array, simply use that value's index:
nameOfArray[0]
(^^^ This would return "value1" ^^^)
So, if you think about it, that makes arrays very for-loop-friendly, so therefor this example looks very simple. Simply use the following to assign every variable in your array to the same value:
for(let i = 0;i < nameOfArray.length;i++){
nameOfArray[i] = "Whatever value I want.";
}
Option 2:
Use an object. An object is basically a group of named variables. The name of the variable is called the "key" and the value of the variable is called the "value". This is usually called a "key/value pair" For example:
var nameOfObject = {
variable1: "value1",
variable2: "value2",
};
Where "variable2" is a key, and "value2" is a value.
Then you can access each variable inside the object using simple dot or bracket notation.
Dot notation: nameOfObject.variableName
Bracket notation: nameOfObject["variableName"]
Setting all variables inside an object to the same value can be tricky. To do so, I usually use a for loop that iterates through all the keys in an object, and sets their values. In order to do so, you will first need to collect all the names of all the keys in the object. I simply use: Object.keys(nameOfObject) then I iterate through that array and assign each variable a value:
const objectKeyNames = Object.keys(nameOfObject);
for(let i = 0;i < objectKeyNames.length;i++){
nameOfObject[objectKeyNames[i]] = "Whatever I want to set it to.";
}
And it's that simple! All variables inside the object will be set to "Whatever I want to set it to."

it sounds like you are looking for a map rather than a list.
if you declare an object
var bubbles = {}
you can then access items by name
bubbles['bubbles1'] = 'something';
you can also loop through the items like a list later if you need to.

you can assign using left hand assignment like this:
let L1 = L2 = L3 = R1 = R2 = R3 = "something";
however that will cause a scope issue.
it would be better to declare then assign like
let L1, L2, L3, R1, R2, R3;
L1 = L2 = L3 = R1 = R2 = R3 = "something";`

Are you sure that you have like hundred variables that are not in fact parts of object?
Like let R1,R2,R3,L1,L2,L3 could be volume {left, right} for 3 audio track.
So you can write
let tracks = [{ right : 0, left : 0}, { right : 0, left : 0}, { right : 0, left : 0}]
L1 will become tracks[0].left and R3 will become tracks[2].right
With 100 tracks?
let tracksCount = 100;
let tracks = new Array(tracksCount).fill().map( t => ({ right:0, left: 0 }) );
Helping?

Related

Why javascript "for loop" has different behaviours for different type of objects

I realise JavaScript has no pointers, however I noticed this "pointer" behaviour when looping through arrays that contains objects, but not the similar behaviour when an array contains numbers (for instance).
var ARR_num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (var i = 0, len = ARR_num.length; i < len; i++) {
var item = ARR_num[i];
item++;
}
console.log(ARR_num);
//Outputs [0,1,2,3,4,5,6,7,8,9]
Now with an array with objects
var ARR_obj = [{}, {}, {}];
for (var i = 0, len = ARR_obj.length; i < len; i++) {
var item = ARR_obj[i];
item.pointer = true;
}
console.log(ARR_obj);
//Outputs [{pointer: true}, {pointer: true}, {pointer: true}]
Why these two distinct behaviours?
Why these two distinct behaviors?
when you assign an object to another variable, the new variable points to same objects hence when you change new variables properties, the Objects gets mutated
example:
var a= {name: "some"};
var b = a;
b.name = "newName";
console.log(a.name);// "newName"
when you assign a primitive type to another variable, its just a new variable and has no reference to old variable, hence changing new variable won't affect old one.
example:
var a = "some";
var b = a;
b = "newName";
console.log(a);//"some"
hope this will help!!
{} is the object literal syntax, which creates (in your case) new objects in an array. When looping through it and using ARR_obj[i], you get the referenced object, which is then manipulated.
Or to put this in other (more general) words:
Primitives (undefined, null, boolean, string and number) are passed by value, while Objects are passed by references (or to be precise by a copy of the reference).
Why these two distinct behaviours?
Because you have two distinct operations. In the latter, you're mutating object's state
item.pointer = true;
item keeps pointing at the same object. Only the internals of the object are changed.
But here
item++; # equivalent to item = item + 1
you reassign item. It will point to another integer after the operation. If you do a similar operations in the object loop
item = { pointer: true }
Then your original array elements won't be affected, and you won't observe any "pointer semantics".
And yes, it also has something to do with integers being primitive/immediate values.
As we know, All values (that are not primitives) are object pointers.
So item is an object pointer in use case 2 where as in use case 1 its integer.
In use case 2, its referring to value "true" for all iteration . so as per code written its giving currect result.
in general JavaScript does not support passing parameters by reference, so using Objects in Javascript , we can pass a reference.

how to create array of json object without key in javascript

I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.

JavaScript Object declaration by combining two different keys

I'm not sure if it's possible or not. So here I'm looking for an answer.
Is there any way to declare an object like:
var objectName = {
key1 : 'value1',
key2,key3 : 'value2;
}
I'm trying to combine key2 and key3 together.
If you don't want to assign the values like Patric Roberts says, create an array of keys and set the same value to those keys like so:
var obj = {};
obj['key1'] = 1;
// Array of keys
var arrayOfKeys = ['key2','key3','key4'];
// Common value for keys in array
var val = 2;
// Iterate the array
for(var k in arrayOfKeys) {
obj[arrayOfKeys[k]] = val;
}
console.log(obj);
You can also check this answer
You could use a slightly different approach, which will work on primitive values, too, by adding an object for keeping the same reference to different keys in the array. For example, you have a value object, like
temp = {
value: 42
}
and an array, like
object = {
key2: temp,
key3: temp
}
then you can use the keys independently for the value of the referenced object.
To change the value, you need to address it with
object.key2.value = 2000;
console.log(object.key3.value); // 2000

Javascript associative array how to map multiple strings to a number

Javascript newbie here. I currently have an associative array in the following format:
StringA: number,
StringB: number
Is it possible to map multiple strings to the same number? Something like this (some numbers may have a different number of Strings mapped to them):
StringA, StringB, StringC: number,
StringD, StringE: number,
StringF, StringG, StringH, StringI: number
Basically, I want holder to have the same value whether I write var holder = arr[StringA] or var holder = arr[StringC]. If it's not possible could someone point me in the right direction? Any help would be greatly appreciated!
You could use an object with a value for the object with multiple keys for one object.
Basically this creates a reference to the shared object. Then you could change the value inside of the object.
var temp = { value: 42 },
object = {
a: temp,
b: temp,
c: temp
};
console.log(object.a.value); // 42
object.b.value = 7;
console.log(object.c.value); // 7
Basically Js don't have associative array they are objects. Read this:
http://www.w3schools.com/js/js_arrays.asp
You need pointers to achive this, but JS not have pointers. But ther is a way to use pointers: use objects.
var assoc = [];
assoc["stringA"] = { value: 1};
assoc["stringB"] = assoc["stringA"];
assoc["stringC"] = assoc["stringA"];
assoc["stringD"] = { value: 10};
assoc["stringE"] = assoc["stringD"];
console.log("A: "+assoc["stringA"].value);
console.log("B: "+assoc["stringB"].value);
console.log("C: "+assoc["stringC"].value);
console.log("D: "+assoc["stringD"].value);
console.log("E: "+assoc["stringE"].value);
console.log("======== modify value ======");
console.log("\nModify A to 2")
assoc["stringA"].value = 2;
console.log("B: "+assoc["stringB"].value);
console.log("C: "+assoc["stringB"].value);
console.log("\nModify E to 20")
assoc["stringE"].value = 20;
console.log("D: "+assoc["stringD"].value);
console.log("E: "+assoc["stringE"].value);

How does Javascript associative array work?

I am in bit of a puzzle, recently I had worked on a project where use of javascript was necessary. Everything is working fine I just need to know how does it work
eg : I had a dynamic variable count, which use to get some value, lets say I get the value as var count = 6;
Now when I put this in array {count : count }
I get the output as {count : 6}
Now my doubt is the output should have been { 6 : 6} as count should have been replaced with its value but it didn't happen so. Why is happening ? and how is this working properly ?
The key value pairs treat the key as a literal and the value as a variable.
so:
var count = 6;
var o = {count: count}; // results in {count: 6}
but to use a variable as the key, you can do this:
var count = 6;
var o = {};
o[count] = count; // results in: {6: 6}
The JavaScript object initialisation syntax lets you use bare words. If you do this:
{ foo: 6, bar: 12 }
It's equivalent to this:
{ 'foo': 6, 'bar': 12 }
What you want is to assign directly, like so:
var foobar = {};
foobar[foo] = 6;
foobar[bar] = 12;
In JavaScript associative arrays (or most associative arrays for that matter), the left side is the key, and the right side is the value. -> {key:value}
When you put {count:count} when you have a count variable beforehand (let's say its value is 10), what will happen is it will be read as {count:10}.
The left-hand side, or the key, is not a variable, but a constant.

Categories