Javascript, jquery - Call array position by using a variable name - javascript

I have 2 arrays:
var array1 = [50,60];
var array2 = [120,180];
I am passing a value to a variable like this:
var curId = $(this).attr('id');
I want to set the content of #result to a computation like this:
$(#result).text(number * curId[0]);
Number is a variable predefined by me, and curId[0] shoul actually translate to array1[0] or array2[0], depending on the css class.
Can anyone tell me the right syntax for this? I'm pretty noob at js.
Thanks.

You can use a variable to hold the array that you want to use:
var myArray;
if (something)
myArray = array1;
else
myArray = array2;
$('#result').text(number * myArray[0]);
If you're trying to get the array in a variable from a string containing the name of the variable, you should use an object, like this:
var arrays = {
array1: [50,60],
array2: [120,180]
};
var myArray = arrays[curId];
$('#result').text(number * myArray[0]);

So curId will be the string "array1" or "array2"? Then you'd do it like this:
var lookups = {
array1: [50, 60],
array2: [120,180]
};
var curId = $(this).attr('id');
$('#result').text(number * lookups[curId[0]]);
What that does is create an object (lookups) to contain this information you're looking up. That object has the properties array1 and array1, which are your arrays. You get the string "array1" or "array2" from the ID of your element into the variable curId, and then you use the fact that Javascript lets you look up properties by their name using [] syntax. All of these are the same:
a = lookups.array1;
// is the same as
a = lookups["array1"];
// is the same as
a = lookups["array" + "1"];
// is the same as
s = "array1";
a = lookups[s];
Technically, if your arrays are declared at global scope, you could do that without using the lookups object, but if you're fairly new to Javascript I won't go into why, and regardless, I'd recommend using one.

Related

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

Named objects and collection of them

not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Getting Length of Object in Javascript / jQuery

I am trying to set up an array in jQuery and I then need to do a for loop on it. But it seems that I cant use an associative array for some reason?
var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;
alert(items.length);
This is just a test, but it return 0?
You can't make associative array in JavaScript like what you want, instead you can use Object.
For example:
var items = {
foo : 123456,
bar : 789012,
baz : 345678,
bat : 901234
}
And to calculate the length you can do:
var getObjectSize = function(obj) {
var len = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) len++;
}
return len;
};
Use: getObjectSize(items); // output: 4
For more see here.
Another one is:
Object.keys(items).length;
But not supported by all browsers.
var items = new Array();
items['foo'] = 123456;
The problem lies in the very first line. You believe that you are adding an item to the array at the index foo, but you are actually adding a property to the items variable with a key foo and value 123456. If you were to type items.foo it would give you back your 123456.
The problem with this approach is that adding a property to an array does not magically increase it's length.
If you want to have non-numeric indexes, you need to use an object instead of an array:
var items = {
foo: 123456,
bar: 789012,
baz: 345678,
bat: 901234
};
Another approach might be to set up two different arrays, which you construct in parallel:
var items = [], items2 = [];
items.push('foo');
items2.push(123456);
// etc.
alert(items2.length);​
The efficiency of this approach depends on how you'll use it. If you're only going to loop through the list of items and do something to each of them, this approach may be more efficient. But if you need to use it like an associative array (items['foo']), then you're better off building an object.
The .length property returns the highest numerical index of the array. Thus, in your case, there is no numerical index and it returns 0. Try
items[98] = "something";
items.length will be 98..! Use the .length property with caution, and if you also want to count the non-numerical indici, loop over the Object (an Array is also an Object) and count its ownProperties.

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

JavaScript Variable Declaration

This is a really stupid question, but I'm just drawing a blank here...
What type of variable declaration is this:
var s1 = [1,2,3,4]
Also, How can I construct a variable like this from multiple objects when the amount of those objects is unknown. This is what I came up with, which doesn't work.
var s1 = [];
for(x in data[i].uh) {
s1 += data[i].uh[x];
}
var s1 = [1,2,3,4]
is an array declaration of four integers using "Array Literal Notation"
You don't need a loop to copy the array, simply do this:
var s1 = data.slice(0);
or in your example you might want this:
var s1 = data[i].uh.slice(0);
Read more about copying arrays here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165
"The slice(0) method means, return a
slice of the array from element 0 to
the end. In other words, the entire
array. Voila, a copy of the array."
That is called an Array, which can be declared with new Array() or by using the array literal [] as in your example. You can use the Array.push() method (see docs) to add a new value to it:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
This
var s1 = [1,2,3,4]
is an array declaration.
To add an element to an array, use the push method:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
s1 is an array, it's a proper Javascript object with functions.
var s1 = [];
is the recommend way to create an array. As opposed to:
var s1 = new Array();
(see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays)
To add items to an array use s1.push(item) so your code would be:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
As a side note, I wouldn't recommend using for-in, at least not without checking hasOwnProperty.
It's declaring a local variable with an Array with 4 members.
If you want to append to an Array, use the push() method.
That is an array. To add to arrays you would use Array.push(). For example:
var s1 = [];
s1.push(1);
s1.push(2);

Categories

Resources