Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print javascript objects?

I have an object

var object= {}

I put some data in the object and then I want to print it like this

document.write(object.term);

the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.

How would it be done?

Update:

this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code

var numCardsStr = selenium.getText("//div[@id='set-middle']/div[2]/h2");

var numCards = numCardsStr.substr(4,2); 

browserMob.log(numCards);

var flash = {}

for(i=0; i<(numCards); i++){

var terms = selenium.getText("//div[@id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[@id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");

flash[terms] = defs;

browserMob.log(flash.terms);

}
like image 903
chromedude Avatar asked Apr 07 '26 05:04

chromedude


2 Answers

EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.

Try:

var flash = {};

...

flash[terms] = defs;

browserMob.log(flash[terms]);

If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.

Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)

var object= {};

object.someProperty = 'some value';

var term = "someProperty";

document.write( object[term] );  // will output 'some value'
like image 166
user113716 Avatar answered Apr 08 '26 20:04

user113716


If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.

There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.

like image 42
Robusto Avatar answered Apr 08 '26 19:04

Robusto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!