How do I assign a value to a variable name stored in an array - javascript

Let's say I have an array with variable names:
var array = [a, b, c];
How can I assign a value to the variable names stored in this array?
For example I want to assign a value of 5 to "a".
I managed to do this in Python by:
globals()[Array[0]]=value
I would like to achieve the same result in JavaScript.
Thanks a lot

Related

Dart Variable store reference to the value

I just started learning about Dart.
Before Dart, I worked with Javascript and have some experience.
Now, as I was going through the documentation from Tutorial Point. They have mentioned something like this
All variables in dart store a reference to the value rather than
containing the value. The variable called name contains a reference to
a String object with a value of “Smith”.
In Javascript, I guess arrays and objects are reference types.
Meaning, If we do something like this
[Update:] This code snippet is incorrect
let a = ["apple", "orange"]
let b = a
a = ["banana"]
console.log(b) //["banana"]
but that is probably only for objects and arrays in JS (and not for const and let)
let a = 5
let b = a
a = 7
console.log(b) //5
From the quote,
All variables in Dart store a reference to the value
[Question:] Does this mean that even things like int, string.. and every variable we create in Dart are references? and the equivalence of the above code will print 7 in Dart or I am getting something wrong (in general)?
let a = 5
let b = a
a = 7
console.log(b) //7
Everything is an Object in Dart. Some objects are mutable - that is they can be modified, and some are immutable, that is they will always be the same value.
When you assign with var b = a; both b and a will reference the same Object, but there is no further association between the names b and a. If you mutate that Object by calling methods on it or assigning to fields on it (things like List.add for example) then you will be able to observe the mutated Object through either name b or a. If you assign to a then the variable b is unaffected. This is true in javascript as well.
The reason some types, like numbers or Strings, appear special is that they cannot be mutated, so the only way to "change" a is to reassign it, which won't impact b. Other types, like collections, are mutable and so a.add("Banana") would be a mutation visible through either variable referencing that list.
For example, with assignment:
var a = ['Apple', 'Orange'];
var b = a;
a = ['Banana']; // Assignment, no impact to b
print(a); // [Banana]
print(b); // [Apple, Orange]
With mutation:
var a = ['Apple', 'Orange'];
var b = a;
a.clear(); // Mutation, the _list instance_ is changed
a.add('Banana') // Another mutation
print(a); // [Banana]
print(b); // [Banana]

Value of variable not getting updated after assignment

var a = 2;
var b = a;
console.log( b ); //2
a= 5;
console.log( b ); //2
Q: Why variable 'b' is getting value 2 even when variable 'a' is assigned a different value
console.log(b) returns 2 because when you access a primitive type you work directly on its value.
Cause numbers are immutable.
Changing an immutable value, replaces the original value with a new value, hence the original value is not changed (thats why b = 2).
If you need a reference, use object and/or arrays
var a ={value: 2}, b = a
a.value = 3 // also changes the value of be, since it can mutate
In javascript, primitives (number, bool, string) are assigned by value, only objects are assigned by reference.
In Javascript, integers are immutable. It means that the object's value once assigned cannot change. When you do
a=5;
b=a;
It is true that both are names of the same object whose value is 5.
Later when you do -
a=2
It assigns the reference a a new object whose value is 2. So essentially a now points to a new object. Ans both objects exist.
For a better understanding you can refer to this link
When doing Assignment of primitive values in javascript:
It's important to point out that this assignment does not tie a and b together. In fact all that happened was that the value from a was copied into b, so when we go to change a we don't have to worry about affecting b. This is because the two variables are backed by two distinct memory locations – with no crossover.
In brief way:
When you assign b = a
Actually you didn't copy the reference of a variable and make b point to the same variable location in memory.
You only copy the value of a variable and put it in new variable b with different memory location.

Javascript: Functions and arrays as key/value pairs

1) In some other languages define function as parameterized block of statements, and on syntactic level javascript function also looks like this, until it's said that it can have it's own properties and methods.How can it be syntactically represented as key/value pair? And where does function code live?
var x = function(a,b){alert('Hi');};
// x = { _code: "alert('Hi'), _arguments: {a:.., b:..,}}
here code and arguments are my imaginary internal properties
2) If array is key/value pair, can i think that array indexes are just object keys?
var a = ["elem1", "elem2"];
// a = {0: "elem1", 1: "elem2"}
Expanding on my comment that EVERYTHING in JavaScript is a object.
var arr = [
function () {
console.log("Well... Look at that.");
}
];
var obj = arr[0];
obj();
var newObj = Object.assign({}, arr);
console.log(newObj);
newObj[0]();
How can it be syntactically represented as key/value pair?
It can't.
The executable code of a function is not expressed in terms of properties on an object.
And where does function code live?
That's an implementation detail of the JavaScript engine, not something that is exposed to JavaScript code in a standard way.
If array is key/value pair, can i think that array indexes are just object keys?
They are just properties. See the specification:
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 232. The value of the length property is numerically greater than the name of every property whose name is an array index;
… and so on.

Access JavaScript object at position/key 0

I am trying to access parts of a JavaScript object where the highest level key is 'randomly generated'. Basically instead of referring to the object as:
json.keyName[0].somethingElse.somethingElseElse[0]
I want to access it by:
json[0][0].somethingElse.somethingElseElse[0]
because I can't predict the keyName value.
Is there an easy way to do this?
You can get hold of a key without knowing its name using Object.keys.
Object.keys({ a: 1, b: 2, c: 3 });
// returns [ 'a', 'b', 'c' ]
We can use this to get the first key out of an object and look up the corresponding value.
var firstKey = Object.keys(obj)[0];
console.log(obj[firstKey]);
However, the order in which the keys end up in the array is not guaranteed to be the same as in the initial object. As an object is much closer to a traditional map than a sorted map.

Can I create dynamic variable names in jade using an array of string values for an object?

I have an array of values named values. I have an each statement that I am iterating through the array. Within the each statement I am using a for loop to iterate through an array of objects. When I iterate through the objects I want to check and see if they have a true boolean variable that shares the name of the items in my values array.
- var values = ["u10","u11","u14","u17","u18"];
each val in values.length ? values : ['There are no values']
-for obj in objects
if obj.val == true
[do something here]
My if statement is currently not working. Does anyone know how to write this if statement in Jade? Each object has a boolean variable that corelates to the values in the list. A model for the objects looks like so:
{"object":{
"u10":true,
"u11":false,
"u14":true,
"u17":false,
"u18":true
}
}
If I write the if statement with the hardcoded variable name such as
if obj.u10 == true
it works properly.
obj.val will literally look for a property named "val" on the object obj, as if obj = {val: true} were the object.
What you need is obj[val] which will interpolate the variable val's actual value and use that to look up that property name

Categories

Resources