How can I print javascript objects?

I have an object

var object= {}

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

document.write(object.term);

term - a variable that varies depending on different situations. When I try to print this, it comes with undefined.

How to do it?

Update:

this is the code I'm dealing with. I think this is probably not the same as what I said above, because I do it in selenium using a browser, I just thought it would look like 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);

}
+3
source share
6 answers

EDIT: , flash flashcards. , , [], ..

Try:

var flash = {};

...

flash[terms] = defs;

browserMob.log(flash[terms]);

term - , , , .

: http://jsfiddle.net/xbMjc/ ( document.write)

var object= {};

object.someProperty = 'some value';

var term = "someProperty";

document.write( object[term] );  // will output 'some value'
+3

document.write(), , . : document.write(), . , script .

, .

+3

, JSON library:

<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>

.

var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));

4 , .


, :

var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;

:

{
    "abcd": "1234"
}

(.. "abce" ), :

for (var key in flash) {
    document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}

:

Key "abcd" has value "1234"
+2
  • document.write

  • Firefox, firebug api

  • apis .

  • IE js

  • javascript obj.propertyname , . , :

pn , obj [pn] .

+1

:

var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
    output = [];
    for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
        output.push([name, this[name]].join(':'));
    }
    return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);

// should look like:
/*
    {
        prop1:0.12134432,
        prop2:lol
    }
*/

, , MyObj:

var MyObj = function(id) {
    this.someIdentity = id;
};
MyObj.prototype.toString = function() {
    return '<MyObject:'+this.someIdentity+'>';
};

-

document.write(new MyObject(2));

<MyObject: 2>.

+1

firefox Chrome/Safari ...

var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);

- "Object"

Chrome, , .

If you are using firefox, the exit should also exit firebug ...

I declare this as an alternative to using document.write, as it seems a bit invasive to the output of content in a document ...

0
source

Source: https://habr.com/ru/post/1765436/


All Articles