i have two arrays defined like these
var theory= new Array();
var first;
var second;
function arrTheory () {
this.first= first;
this.second= second;
}
var subject= new Array();
...
function arrSubject () {
...
this.theory= theory;
...
}
how can i access to the elements in the theory array inside the bigger one?
I've tried
subject[0].theory.first;
but it doesn't work while
subject[0].name;
which is another field of the big array works fine. what i've missed?
I think the point is, you have an array with element as "obj" and added to another array.
So to access to a you could try
subject[0].theory[0].first;
I mean access to element of array by index and them access to the element of the object.
Ok, I have a good guess given the information you've provided.
theory in subject[0].theory is an array, right? How come you are using it like subject[0].theory.first? You should use an indexer like subject[0].theory[0].
In the code you showed us (before any potential edits), you don't add anything to the var theory= new Array();
Also beware to make sure that this is what you really expect. In JavaScript, the context of this changes depending on context of the caller and that's confusing sometimes.
subject[0].theory[0].first;
try that.
Using this in arrTheory() and arrSubject() will cause a syntax error because they are functions not objects and you need rather to set those properties to theory and subject arrays instead so you must use the correspondent array name instead of this like following:
var theory= new Array();
var first = "first";
var second = "second";
function arrTheory () {
theory.first= first;
theory.second= second;
}
var subject= new Array();
function arrSubject () {
subject.theory= theory;
}
arrTheory();
arrSubject();
alert(subject.theory.first + " / " + subject.theory.second);
then you can access first and second properties like this:
subject.theory.first
subject.theory.second
in the code above property name is not set in subject, if it's already set in the original code you can call it like this:
subject.name
jsfiddle
Related
I have a question regarding variables in Javascript.
When I assign a var to a ID I do it like this:
var x = document.getElementById("div_name");
But I would like to make a variable which consists of multiple 'divs'.
I thought this might work but I does not:
var x = document.getElementById("div_name"),document.getElementById("div_name2");
Can someone please help me find the right code syntax and explain why the syntax I tried is incorrect.
So, If you just want them as a list of div's you could do this:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
Just wrap them up with [].
If your var should contain more than one object (div in your case), then you need to have more variable or, better, an array.
You can create yor array by using following code.
var x = [document.getElementById("div_name"), document.getElementById("div_name2")];
This is due to the fact that different DIVs in the DOM page are different objects...
There is no such variable that is defined as:
var x = somthing, somesthingElse
You need to chose a variable that can store a collection of "things". In your case the Array is an ideal choice:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
The brackets at the beginning and end of the expression are the syntax to declare a variable.
In addition to using Array, you can also store your divs in an Object
var divs = {
div1: document.getElementById("div_name"),
div2: document.getElementById("div_name2")
};
Thus, you could give a convenient name to your divs, but still pass them around as you please:
divs.div1;
divs.div2;
Or loop through them like so:
for (div in divs) {
console.log(divs[div]);
};
I have a copy button that has:
$scope.copyHeadline = function (headline) {
var headlineCopy = headline;
var current_time = Date.now();
headlineCopy.label = headline.label + ' (Copy ' + current_time + ')';
$scope.headlineList.push(headlineCopy);
}
but I get the "Duplicates in a repeater are not allowed" error. I notice that everyone element in the array or list that i have has some sort of hidden property like:
$$hashKey: "object:135"
which i'm pretty sure is what it's duplicating but I can't change?
I read that I can use:
track by $index
but what ends up happening is that when I push the Copy button, it also edits the original element that I was copying as well so that doesn't work..
I was also of thinking of just creating a whole new element and writing a function that'll literally copy every element into a new one.. but this Class alone has several subclasses with ALOT of properties. So i guess I just wanted to see if there was an easier of doing it before I resort to that method. Thanks!
That is happening because just assigning a reference of the original object to a different variable will not make a copy of it. It just copies the reference to the same object.
AngularJS copy documentation
Use:
var headlineCopy = angular.copy(headline);
This will make a deep copy of the object.
Your problem stems from the fact that you are not copying your headline object, merely referencing it.
It's difficult to know the full solution without knowing more about your headline objects, but you could try something like this:
$scope.copyHeadline = function (headline) {
var headlineCopy = {};
var current_time = Date.now();
headlineCopy.label = headline.label + ' (Copy ' + current_time + ')';
$scope.headlineList.push(headlineCopy);
}
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']
I want to create a new variable in javascript but it's name should made of a stale part and a variable one like this:
tab_counter = 1;
var editor + tab_counter = blabla
well i want the new variable name to be in this case editor1, is this possible?
You cannot create a stand-alone variable name that way (except as a global) (edit or except with eval()), but you can create an object property:
var tab_counter = 1;
var someObject = {};
someObject['editor' + tab_counter] = "bla bla";
You can create globals as "window" properties like that, but you probably shouldn't because global variables make kittens cry.
(Now, if you're really just indexing by an increasing counter, you might consider just using an array.)
edit also see #Birey's somewhat disturbing but completely correct observation that you can use "eval()" to do what you want.
It is possible
var tab_counter=1;
eval("var editor"+tab_counter+"='blah'")
alert(editor1);
eval("var editor"+tab_counter+1+";")
editor2='blahblah';
alert(editor2);
http://jsfiddle.net/5ZLYe/
You can do the eval method used by Birey or you can create a custom property of an object such as...
obj[editor + tab_counter] = blabla;
But it sounds like you're going about doing whatever you're doing in a particularly horrible way. If you just want to store multiple items which you can index into use an array...
var array = [];
array[0] = blabla;
array[1] = blabla2;
alert(array[0]); //shows value of blabla
alert(array[1]); //shows value of blabla2
It seems like you may want to consider using a Dictionary for something like this. This link which references this link describes your options there.
A simple question I'm sure, but I can't figure it out.
I have some JSON returned from the server
while ($Row = mysql_fetch_array($params))
{
$jsondata[]= array('adc'=>$Row["adc"],
'adSNU'=>$Row["adSNU"],
'adname'=>$Row["adname"],
'adcl'=>$Row["adcl"],
'adt'=>$Row["adt"]);
};
echo json_encode(array("Ships" => $jsondata));
...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...
if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
{
WShipsObject = JSON.parse(ajaxRequest.responseText);
var eeWShips = document.getElementById("eeWShipsContainer");
for (i=0;i<WShipsObject.Ships.length;i++)
{
newElement = WShipsObject.Ships;
newWShip = document.createElement("div");
newWShip.id = newElement[i].adSNU;
newWShip.class = newElement[i].adc;
eeWShips.appendChild(newWShip);
} // end for
}// If
You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...
I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.
So how do I do this?
Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...
$(".wShip").click(function(){
var test1 = $.inArray(this.id, newElement.test);
var test2 = $.inArray(this.id, WShipsObject);
//alert(test1+"\n"+test2+"\n"+this.id);
});
For one you can simply use the ID attribute of the DIV to store a unique string, in your case it could be the index.
We do similar things in Google Closure / Javascript and if you wire up the event in the loop that you are creating the DIV in you can pass in a reference to the "current" object.
The later is the better / cleaner solution.
$(".wShip").click(function(){
var id = $(this).id;
var result;
WShipsObject.Ships.each(function(data) {
if(data.adSNU == id) {
result = data;
}
});
console.log(result);
}
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.
In the solution I created a custom attribute called key into which I stored the index.
newWShip.key = i;
Later when I need the index back again I can use this.key inside the JQuery .click()method:
var key = this.key;
var adt = WShipsObject.Ships[key].adt;
You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.