How to write to multiple arrays based off numbers? - javascript

Say I have two arrays and an integer.
var int = 1; //or 0 depending on other circumstances
var ar0 = [0]
var ar1= [1]
Is there a way to use the integer to determine which array to write to? Like if int = 1 then I could have something along the lines of
'ar'+ int
that would choose the correct array? Or do I need a bunch of if-statements?
I'd like to be able to identify and edit the array that I need to edit by a number that was given to me.

What you are trying to do is to set up an environment. However, you cannot access variables in what is called the Variable Environment in JavaScript by name such as with 'ar' + int. If it is in the global scope that is kind of possible by using window['ar'+int] but this is bad practice and also assumes that the variable is global.
What you should do is wrap those in an object and then use the reference in the object to locate the array.
var int = 1;
var environmentObject = {};
environmentObject['ar0'] = [0];//string notation assignment example
environmentObject.ar1 = [1];//dot notation assignment example
and now you can easily access your array by name
var myarr = environmentObject[`ar`+int];

You could use an eval
var int = 1;
var ar0 = [0];
var ar1 = [1];
eval('ar' + int).push(2);
console.log(ar1); // 1, 2
But it is a bad practice. For your case, if you have only two integers(0, 1) better to use if statement:
if(int) { // 0 is falsy, 1 is truth
ar1.push(...);
} else {
ar0.push(...);
}
Or as Oriol mentioned, using ternary operator:
(int ? ar1 : ar0).push(...);

Related

Variables and functions from String in JavaScript

For instance, we have a variable and a function named foo and plus:
var foo = 2;
var plus = function(a,b){return a+b;}
and we have a string:
var s = '1 plus foo';
and now I want this string s convert to an array:
var array = [1, plus, foo]);
Please note this is not [1, 'plus', 'foo'] which conversion is rather easy and I know the way.
So, consequently, my Question would be
how to obtain a value(function) itself from strings?
and also please note that using eval to solve this issue is invalid since the purpose is not to evaluate but to construct an array from the string.
Thanks.
EDIT:
Since I use node.js
The global object is global
and
it seems
global.foo and var foo is different.
I felt that before this Question and that is why I asked here.
[1, global['plus'], global['foo']] should be invalid answer.
if you do s.split(' ');, you can use the strings in the array to call the requested functions:
window['plus']() // Call your functions like this.
Or to set them in an array:
var array = [1, window['plus'], window['foo']];
Then you'll have the function references stored in array.
My self answer:
var G = {};
var foo = G.foo = 2;
var plus = G.plus = function(a,b){return a+b;}
and we have a string:
var s = '1 plus foo';
and now I want this string s convert to an array:
var array = [1, G['plus'], G['foo']];
In this way, we can avoid Global Variables and keep var foo format, and at the same time, allow the value accessible with G object + ['string'].

Javascript Objects (dynamic attribute names)

if I have an object, something like this
var o = {
test : 1
}
and I would like to have a second object, one of it's keys should be the value of o.test.
Something like this:
var o2 = {
o.test : "bla"
}
I know this is not possible, but is there a better (cleaner) way to do it as I do this now?
Currently what I dow is this:
var o2 = {};
o2[o.test] = "bla"
I guess there is a better way for this?
I guess there is a better way for this?
Assuming I've understood your question correctly then no, not really. The way you've shown is the way to do it. There is no way to use a dynamic key inside the literal itself, so you have to declare it first and then assign the property separately:
var o2 = {};
o2[o.test] = "bla";
o2; // { 1: "bla" }
Update
The full details are given in the spec. Here's the grammar for object literal property identifiers:
PropertyName :
    IdentifierName
    StringLiteral
    NumericLiteral
The StringLiteral production is self-explanatory. Here's what the IdentifierName production does:
The production PropertyName : IdentifierName is evaluated as follows:
Return the String value containing the same sequence of characters as the IdentifierName.
And for the NumericLiteral production:
The production PropertyName : NumericLiteral is evaluated as follows:
Let nbr be the result of forming the value of the NumericLiteral.
Return ToString(nbr).
You can see from this that it is not possible to use anything other than a string inside an object initialiser.
Your Object properties can be any string
var o = {
"whatever you want":1,
"1":"numbers too"
}
o[2]="no numbers, convert to string"
console.log(o["whatever you want"]);//=1
console.log(o["1"]);//=numbers too
console.log(o[new String(2)]);//=no numbers, convert to string
// as James commented, you don't have to convert to string
// I usually do that as to not confuse the object with an array
console.log(o[2]);//=no numbers, convert to string
If all your "property names" are positive integers or 0 you could use an array:
var arr=new Array();//or var arr=[];
var b=22;
arr[10000]="hi";
arr[b]="value";
// normally you would do for(var i=0;len=arr.length;i<len;i++){...arr[i]
// but because there may be many empty spots it's quicker to do:
for(thing in arr){
if(arr.hasOwnProperty(thing)){
console.log(thing + " is " + arr[thing]);
}
}
This being javascript, there is almost always a workaround for doing what you want.
There is no syntax for doing what you want but you can certainly write a function to do it:
function make () {
// Optional sanity check:
if (arguments.length % 2) throw "Number of arguments should be even!";
var obj = {};
for (var name=0,val=1; name < arguments.length; name+=2,val+=2) {
obj[arguments[name]] = arguments[val];
}
return obj;
}
Now you can write this:
var o2 = make(
o.test, 'bla',
'another_key', 'another_val'
);

Two Dimensional Array in Javascript Object

I want to create an Object that contains one or more two dimensional arrays in Javascript.
I tried it the following way (in this example I only try to add one two dimensional array):
var XSIZE = 8;
var YSIZE = 8;
var obj = {
field : new Array(XSIZE),
field[0] : new Array(YSIZE),
foo : 1,
bar : 100
}
Info:
- This gives me a strange error "missing : after property id" which does not seem to make much sense
- Unfortunately I didn't find examples showing how to do this so far by using google
- If I don't add field[0] ... for creating the 2nd array it works.
- changing the XSIZE and YSIZE to numbers like new Array(8)... doesn't work.
I would really appreciate if somebody could show me how to do it or explain why I cannot do this at all and need to use some other method.
Thanks a lot!
The error "missing : after property id" is because JavaScript sees the field part of field[0] and expects a colon before the value of that field. Instead it gets an open bracket so it complains.
You can't hard code an object definition that has its dimensions set up at run time. You have to build the object at run time as well. Like this perhaps
var XSIZE = 8;
var YSIZE = 8;
var obj = {
field : new Array(),
foo : 1,
bar : 100
}
for (var i = 0; i < XSIZE; i++) {
obj.field.push(new Array(YSIZE));
}
In object literal notation, the property names must be exactly that: property names. Firstly, field[0] isn't a property name. Secondly, the properties don't exist until the after the object defined, so you can't access properties until then.
What you should do is either set the array after the object is created:
var obj = {...}
obj.field[0] = [...];
or nest the array literals:
var obj = {
field: [ [...],
...
],
...
}
You don't need to worry about setting the array size when creating the array, as it will grow when you add elements.
You can only declare properties on the object being constructed that way; not on objects in another "level".
You could use a for loop instead:
for(var i = 0; i < XSIZE; i++) {
obj.field[i] = new Array(YSIZE);
}
Note that the YSIZE is not necessary since an empty array works just fine as well ([]).
You could get the two dimensional array as your obj property, without resorting to external procedures and keep everything internal to the object. Create your empty 'field' array 1st.
var obj = {
field:[],
foo:1,
bar:100
};
Now, create an object's method to create a two dimensional array off your initial dimensionless array. You can determine the length and the number of dimensions of multi dimension array as you wish at run time:
var obj = {
field:[],
multifield:function(x,y){for (var count=0;count<x;count++) {this.field[count]=new Array(y);}},
foo:1,
bar:100
};
You can then call the obj.multifield method entering whatever dimensions you decide:
obj.multifield(10,5); //-->create a 10x5 array in this case...
console.log(obj.field.length); // 10
console.log(obj.field[0].length); // 5

Using Strings as KEY of map in javascript

Im using this 'map' on js:
var myMap = new Object();
myMap[key1]=value1; //like this n times...
but i want to use the key as some combination of two strings meaning:
function getMapValue(str1,str2){...}
i dont mind joining the two strings into one long string and use the function with the long string
any ideas?
You can make a map of maps (just be sure to check that the intermediate map exists when accessing it)
var myMap = {}; //dont use "new Object()". It is evil.
function insert(k1, k2, v){
if(!(k1 in myMap)){ myMap[k1] = {}; }
myMap[k1][k2] = v;
}
function get(k1, k2){
return myMap[k1] && myMap[k1][k2];
}
And if you want to join two substrings into a single one you can use the plus operator to concatenate things.
var customKey = k1 + '|' + k2;
Just be sure your separator can't be used in a normal key to avoid conflicts.
If I got you right, the following should help:
var myMap = {"key1" : "something1", "key2" : "something2"};
to get value for a key, you you use, either: return myMap.key1;
Or: return myMap.["key1"];
If you had/did: myMap["key1key2"] = "MagicHappens!";
you could use myMap.key1key2 to get the value or myMap["key1key2"], or even: return myMap["key1"+"key2"];
Or:
var x = "key1";
var y = "key2";
return myMap[x+y];
in your getter function, you get the two variables for the keys which you can then directly use.

variable as index in an associative array - Javascript

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:
var arrayName = new Array;
arrayName["indexName"] = value;
// i know i can also do the last line like this:
arrayName.indexName = value;
When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:
arrayName[eval("nume")] = value;
Where:
var var1 = "index";
var var2 = "Name";
var nume = '"' + var1 + var2 + '"';
but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"
Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?
At first I don't think you need a real array object to do what you need, you can use a plain object.
You can simply use the bracket notation to access a property, using the value of a variable:
var obj = {};
var nume = var1 + var2;
obj[nume] = value;
Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.
True arrays are useful when you need to store numeric indexes, they automatically update their length property when you assign an index or you push a value to it.
You would use objects to do that:
var hash = {}
hash["foo"] = "foo";
hash.bar = "bar";
// This is the dynamic approach: Your key is a string:
baz = "baz"
hash[baz] = "hello";
To iterate, just use a for loop or $.each() in jQuery.
use arrayName[var1+var2]
Note that arrayName.var is the same as arrayName["var"] -- it's just syntactic sugar. The second form is mostly used when dealing with the kind of problems that you are facing - dynamic object keys, and keys that are not alphanumeric (think of arrayName[".eval()"]; this is a perfectly legal object key that has nothing to do with the javascript eval() function)
Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?
And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';
You want a plain object with the same bracket notaiton here, like this:
var arrayName = {};
arrayName["indexName"] = value;
Indeed, there was no need for an array object, a simple object did the job; further more an array introduced the need to use quotes inside the square brackets obj["var1 + var2"] to access the object property's value and not the value associated with an index (i think); the quotes transformed "var1 + var2" into a string. Using a simple object eliminated the need for quotes, so I can use obj[var1 + var2], wich worked :)
Thanks everyone !
I did something like like following;
let parentArray = [];
let childArray = [1, 2, 3];
childArray.name = 'my-array-1';
parentArray.push(childArray);
To access that by name in ES6;
parentArray.filter(x => x.name == 'my-array-1');

Categories

Resources