Declare javascript object property issue - javascript

I am trying to declare a javascript object properties.
I have
var myObj = {};
var rowsCount, columnsCount, texts;
var temp = document.createElement('div');
temp.innerHTML = tableData; //tableData is bunch of tables in html
var tables = temp.getElementsByTagName('table')
//use tables as array...
for(var i = 0; i<tables.length; i++){
var table = tables[i];
myObj.rowsCount = $('tr', table).length;
myObj.columnsCount = $('td', table).length / myObj.rowsCount;
}
The above codes work. However, if I remove
var rowsCount, columnsCount, texts;
the code will complain rowsCount, columnsCount and texts are not defined.
However, in W3Cschool object page, they have
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
and it seems fine without declaring the property first.
Can someone help me out here? Thanks a lot!

myObj.rowsCount is not the same as the rowsCount variable. The first is a property of an object, the other one is just a variable (with the same name).
If you're getting that error (assuming it's a ReferenceError), it's because you're trying to read from the rowsCount variable (not myObj.rowsCount) when it doesn't exist. That must be happening in some part of your code that you didn't show us.

Related

JS- Call a method from a generated button for a specific object

I m new at coding , and I m searching for a way to launch a specific prototype method for each object of my array from a generated button
I've got json data to loop , and include each object on a js array.
//My data got 3 objects
var readArr = JSON.parse(myData)
var js_arr = [];
// loop on the array of object
for (var i = 0; i < readArr.length; i++) {
var generatedObject = new Object();
//init method from prototype
generatedObject.init(readArr[i].prop1, readArr[i].prop2, readArr[i].prop3, readArr[i].prop4, readArr[i].prop5,
readArr[i].prop6, readArr[i].prop7, readArr[i].prop8);
js_arr.push(generatedObject);
//generated a div which will contains a button for each occurence
var newCntent = document.createElement('div');
newCntent.id = readArr[i].prop1 + i;
newCntent.className = "cntent";
document.getElementById('zone_btn').appendChild(newCntent);
//create a button inside the div
var newBtn = document.createElement('div');
newBtn.id = i + readArr[i].prop1;
newBtn.className = "etalonBtn";
newBtn.innerHTML = readArr[i].prop1;
document.getElementById(newCntent.id).appendChild(newBtn);
I've got a prototype method on my Object class and what I want is launch that method for each object linked with a button.
The first generated button will launch the method for js_arr[0], the second for js_arr[2],...how to code the fact that when I click on the button , the method must be call by "the object of the array which permetted your creation"
I don't have any clue on the way I can do this I tried several things:
newBtn.addEventListener('click', function () {
read_arr[i].DisplayUpdate();
});
};
(returning read_arr[i] is not defined), so I just want to change that read_arr[i] by this now famous :"the object of the array which permetted your creation" !
and I really need help on this...
Thank you by anticipation and sorry for this preschool english.
The issue is that when you're getting to the click function (i.e. - when actually clicking the button) you're already out of the loop, so js doesn't know what 'read_arr[i]' is.
You need to pass 'read_arr[i]' as a parameter to the function.
Basically something like this:
newBtn.addEventListener('click', function (object) {
object.DisplayUpdate();
},js_arr[i]);
This will change the function's signiture to also take a parameter- object, and also pass js_arr[i] as that parameter.
Hope that helps
you could also assign and bind the function to call when you create the button in your loop:
var newBtn = document.createElement('div');
newBtn.id = i + readArr[i].prop1;
newBtn.className = "etalonBtn";
newBtn.innerHTML = readArr[i].prop1;
newBtn.onclick = jsArr[i];

Add existing variable to array in javascript

I've got this HTML
<div class="calListChip" id="label-bDd1aDFjNnQ2aHFxOTN2cGQyM2JhaXA2cmtAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ" title="Testkalender1">
<div class="calListChip" id="label-OWFmbmdwbWprbTRxMmFrOTNycGlicmM2bjBAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ" title="Testkalender2">
and I've got this code, creating variables with the title of a html div as name and then I pass the label of the html object as parameter to the variable.
var elements = document.body.getElementsByClassName('calListChip');
var view1 = [];
//For each element found
for (var i = 0; i < elements.length; i++) {
//Variable names cant inlude spaces
var title = elements[i].title;
title = title.replace(/ +/g, "");
//create the variable
window[title] = elements[i].id;
//if 'test' exist in the title, add the variable to an array
if (elements[i].title.toLowerCase().indexOf("test") >= 0)
{
view1.push(window[title]);
}
};
But the view1 array dosent get the variable reference but instead a string with the title name, that I cant use later on.
This is the result I want
view1 : [Testkalender1, Testkalender2]
This is the result i get
view1 : ["Testkalender1", "Testkalender2"]
The problem is that i dont know how many or the title/label of the html elements so i need to dynamically create variables and then by a keyword in the title put them in the right array
Any suggestions?
It is not clear how exactly you want to generate your desired result (e.g. where the data comes from), but I can help explain what is happening with your current code. When you do this:
window[title] = elements[i].id;
You are creating a global variable of name title and assigning it the string value located in elements[i].id. So, now you have a global variable with a string in it.
When you later do this:
view1.push(window[title])
You are just pushing a copy of that string in the view1 array. That string has nothing to do with your global variable. So, view1 will end up being an array of strings.
If you want view1 to end up being an array of objects like your example here:
view1[0] = {
name: 'TestKalendrar',
items: [Testkalender1, Testkalender2]
};
Then, you have to push objects into the array, not strings.
I should add that I have no idea what your creation of global variables with this line:
window[title] = elements[i].id;
is doing to help you with your problem in any way. It should not be necessary.
I'd be happy to help you get a different result, but so far you've shown a desired array of objects, but not shown us where you get the name property from or the items property. If you can edit your question to show where those values come from, we can help with a solution to generate that.
I reworked your code a little and indeed the variables are being created see the fiddle at http://jsfiddle.net/smylydon/Q5m6Q/
var elements = document.body.getElementsByClassName('calListChip');
var view1 = [];
//For each element found
for (var i = 0, length = elements.length; i < length; i++) {
//Variable names cant inlude spaces
var title = elements[i].title;
title = title.replace(/ +/g, "");
//create the variable
window[title] = elements[i].id;
//if 'test' exist in the title, add the variable to an array
if (title.toLowerCase().indexOf("test") >= 0) {
view1.push(window[title]);
console.log('variable:', window[title]);
}
};
console.log('view1:', view1);

accessing nested properties based on structure

Could anyone please give me an alternate syntax to the following
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
var i=0;
for(var k in ResultsContainer)
{
var TheArrayOfObjectsThatIneed = ResultsContainer[Object.keys(ResultsContainer)[i]];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
i++;
}
as you see in the image i have an array within an object within an object and i have no idea what the property names are but the structure is always the same {results:{id:{idthatidontknow:[{}]}}} and all i need is to access the arrays
the above code is working nicely but i am new to javescript and i was wondering if there is a nicer syntax and if i am doing it the right way
Perhaps something like this?
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
for(var k in ResultsContainer) {
if (ResultsContainer.hasOwnProperty(k)) {
var TheArrayOfObjectsThatIneed = ResultsContainer[k];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
}
}

dynamic object properties javascript

Having issues with this code block:
var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');
name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);
If I take out the .val on both lines, the code works. I'm trying to dynamically create the "
nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.
Thanks for any help
When trying to assign
nutrients[name].val = tds[1].innerHTML;
the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use
nutrients[name] = {
val: tds[1].innerHTML
};

Display names of variables (or everything) in window[], html/javascript

I'm trying to make a poor man's Firebug inside of an HTML page. I created an external script that is placed somewhere in the target page. Initialized with <body onload="monitor_init()">. It also brings in a style sheet to absolutely position a partially-opaque table with the results.
So it runs through everything (values) in window[], displays it in one column, as well as the typeof(window[i]) in another column. I'd also like to have another column that displays the name of the variable or object.
function monitor_init()
{
var css = document.createElement("link");
css.setAttribute("href","jsmonitor.css");
css.setAttribute("rel","stylesheet");
css.setAttribute("type","text/css");
document.getElementsByTagName("head")[0].appendChild(css);
var temp = document.createElement("div");
temp.setAttribute("id","monitor_box");
var temp2 = document.createElement("table");
temp2.setAttribute("id","monitor_output");
temp.appendChild(temp2);
document.body.appendChild(temp);
monitor();
}
var monitor_speed = 100;
function monitor()
{
while(document.getElementById("monitor_output").childNodes.length > 0)
{
document.getElementById("monitor_output").removeChild(document.getElementById("monitor_output").lastChild);
}
for (i in window)
{
if (["function","undefined"].indexOf(typeof(window[i]))!=-1)
{
continue;
}
// This is where I tried to make a first column displaying the name, couldn't find anything that worked.
// Disregard the .name, that was just last-ditch stuff
//var temp = document.createElement("tr");
//var temp2 = document.createElement("td");
//temp2.appendChild(document.createTextNode(window[i].name));
//temp.appendChild(temp2);
var temp = document.createElement("tr");
var temp2 = document.createElement("td");
temp2.appendChild(document.createTextNode(typeof(window[i])));
temp.appendChild(temp2);
var temp2 = document.createElement("td");
temp2.appendChild(document.createTextNode(window[i]));
temp.appendChild(temp2);
document.getElementById("monitor_output").appendChild(temp);
}
setTimeout("monitor()",monitor_speed);
}
By using typeof I was able to skip displaying the values of functions and some undefined things. I was hoping that if I could get access to the name I could also skip stuff like the history, location, and other things that aren't JavaScript numbers, strings, array objects, etc., i.e. global variables that I created in other scripts on the page.
You haven't really asked a specific question, but I think you're trying to say "How do I get the name of each property of window?"
In your existing code you're using a for-in loop to go through the various properties. What I think you need to know is that your index variable will hold the name of the (current) property:
for (i in window) {
alert("Property name: " + i);
alert("Property value: " + window[i]);
}
The looping construct you're using will provide this information:
for (i in window) {
// at the point, i is a string containing the name of the property
// window[i] contains the value of that property
document.write('window.' + i + ' is ' + window[i] + '<br>');
}
but as another poster asked - why can't you use firebug lite?

Categories

Resources