Viewing an object - javascript

I am learning JS and after fiddling around with adding elements etc I tried to do an alert() with the object but instead got this error: [object htmltableelement]
so I then tried:
alert(t.toString());
and got the same error... how can I see the contents of the object?

you can use firebug:
console.log(t);
or you can use innerHTML;
alert(t.innerHTML);

The way I normally do this is by using FireBug firefox add-on.
Add a break point in your JavaScript then you can view any object and all its keys/values.

See everything:
for(var key in t)
alert('key:' + key + ', value: ' + t[key]);
You may want to replace alert with console to avoid 100s of alerts

function domObjectToString(domObject){
if(typeof(domObject) ==='object'){
var divElement = document.createElement('div') ;
divElement.appendChild(domObject);
return divElement.innerHTML;
}else{
return domObject.toString();
}
}
---- steps follow -----
1. check the domObject Type [object]
2. If Object than
a. Create an "Div" element
b. append DomObject To It
c. get The innerHTML of the "div" it Gives The String
3. If Not an Object than convert to String and return it .

That is not an error. That is the default string representation of an object.
Either iterate through the object's properties and output them one by one, or use a proper debugging tool like Firebug that'll give you the ability to really examine your variables.

Related

Setting Variable Assignments with property display

I'm still a novice when it comes to JavaScript and was trying to make my code more cleaner and was wondering why the top scenario works but the bottom doesn't? Am I missing something?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
partner.style.display = "none";
providedBy.style.display = "none";
But this does not?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
collection = partner + providedBy;
collection.style.display = "none";
In the console it gives me error saying Cannot set Property 'display' of undefined. Am I supposed to define it somewhere first? I console logged the new variable and it returned both div elements.
collection is of type string as the + operator automatically call for both their toString() function.
Now what you are trying is to access a property of collection.style which does not exist because you are operating on a string. That's the reason for the error message you are getting.
You could do something like:
var collection = [];
collection.push(document.getElementById('partner'));
collection.push(document.getElementById('providedBy'));
collection.forEach(function(element) {
element.style.display = 'none';
}
which would be something I think you are trying to archive.
just to complement the accepted answer, I think you should understand why you get this error.
For what i understand from your code, you are trying to set the css of both variables partner and providedBy to display : none.
Your first piece of code works because you do this separately, while in your second code you try to add with the (+) operator both nodes, which evaluates to the string "[object HTMLDivElement][object HTMLInputElement]".
Then you try to call .style on that string which evaluates to undefined, and then you try to call display on that undefined value, this is where you get the error.
You could leave your code just like that since there are not too many variables, but if you wanted to do something that worked on multiple variables you could
create an array
push your objects into the array
create a function that loops over the elements of the array and set their style.display = "none" to individually.
In JavaScript you have to declare all of your variables. Secondly, you can't point to two objects at once by using the + operator. JavaScript interprets this as trying to concatenate the two objects, which it can't do in this way. It will return the string [object Object][object Object]
In order to affect two Objects at the same time you would need to create a function or use an existing method.

Custom string instead of "Object" in console.log

For convenience while debugging, I think it would be nice to print some custom string, rather than the default Object that appears when logging an object to the console.
In the following example, see how an object called example is marked by Object when it is logged to the console, whereas window is marked by Window when it is logged to the console. I guessed that the __proto__["Symbol(Symbol.toStringTag)"] property might be the way to go, since window's is set to Window. That didn't work, but maybe I'm just using it wrong.
That's because you're using the Symbol wrong -- you were on the right track. Symbol.toStringTag is a special well-known Symbol used by Object#toString to give you the console output, specifically the tag you're after. You can't wrap it in a string as you've done, or else you'll be literally setting the "Symbol.toStringTag" property, not the actual Symbol:
const example = {
key: "value"
};
example.__proto__["Symbol.toStringTag"] = "Example";
console.log(example); //You set the literal "Symbol.toStringTag" property -- wrong
Instead, don't wrap it in quotes and actually set the Symbol:
const example = {
key: "value"
};
example.__proto__[Symbol.toStringTag] = "Example";
console.log(example);
Which produces (on Chrome):

trying to work dynamically with object properties in javascript

I'm trying to sort out if this is plausible but have gotten syntax errors at best. So I am wondering if it is at all possible.
What I have is an object (example only)
var myObj = {
something1_max:50,
something1_enabled:false,
something1_locked:true,
something2_max:100,
something2_enabled:false,
something2_locked:true,
something3_max:10,
something3_enabled:true,
something3_locked:true
}
and what I want to do through a function is do something like again for example to sum things up..
function displayDetails(theScope, obj)
{
console.log(obj.[theScope]_max);
}
(function(){displayDetails('something3', myObj);})()
so when displayDetails() is called whatever the scope I can see in this example the max for that scope. In the console log for the example I would hope to see 10
Properties of JavaScript objects can always be accessed as a string using the bracket syntax, ie object['property']. This, of course, means you can build that string dynamically:
console.log(obj[theScope + '_max']);
Put the property name string in brackets.
console.log(obj[theScope + '_max']);

Javascript: String concatenation in object constructor

Been trying to create a JavaScript object member that always contains a common string. Whenever I create a new object, instead of concatenating the string, it overwrites it with the passed value on creation. If it matters (I don't think it does) the string contains numbers. Par example:
function myObj(strToConcat){
this.combinedString = "Hello " + strToConcat, /* have used + and .concat() without success */
}
var newObj = new myObj("1.2.3");
console.log(newObj.combinedString); /* says "1.2.3", the leading "Hello " is absent */
Can't seem to get this to concatenate the strings.
EDIT: I apologize, the error was outside the code that I thought responsible. Disregard please. My apologies.
You have error in your reference
console.log(myObj.combinedString);
should be
console.log(newObj.combinedString);
Running your code gives me SyntaxError: Unexpected token }. Replace the , at the end of the second line with a ; and I get the expected result of "Hello 1.2.3".

Javascript arrays and Meteor session

I have made an interesting observation. When trying to update an array that is stored in the Meteor session storage, the following code will not propagate the changes:
var tags = Session.get("Tags");
tags.push("a");
Session.set("Tags", tags);
But if I change the first line to use Session.get("Tags").slice(), everything depending on the session will update accordingly. I guess this is due to the fact that Meteor tests some references for equality and therefore does not update anything.
Is there a better way to manage lists stored in the meteor session store?
If I now try to remove an element from the collection (using array.remove() from here), the behavior turns out to be a bit ... of ... I am doing this inside a Meteor template event, the code looks like this:
"click .taglist li" : function(e) {
var tags = Session.get("Tags").slice();
var index = cardTags.indexOf(this);
Meteor._debug(Session.get("Tags").slice().indexOf("a"));
Meteor._debug("Removing tag \"" + this + "\", index: " + index, ", typeof(this) = " + typeof(this).toString());
tags.remove(index);
Session.set("Tags", tags);
}
This outputs:
1
Removing tag "a", index: -1, typeof(this) = string
So somehow, the cardTags.indexOf(this); statement seems to return -1 for almost any case. I guess I am doing something fundamentally wrong, as I am quite now to javascript, but somehow I can not figure out whats going on here.
Why will those two calls to indexOf() behave different?
I believe this is the same as this situation in Backbone.js. In order for the change event to be triggered, Meteor needs to have a new reference for the array, not just an updated copy of the old one.
In brief, in order to have the 'correct' behaviour, you'll need to clone the array, make the changes you want, and then do Session.set('foo', myCopiedArray).
In short: Use var index = cardTags.indexOf(this.toString()); instead.
Long version:
When using strings in JavaScript, those are strings, whereas typeof 'test' returns string.
Let's take a look at the following code in order to get find out another way to represent strings in JavaScript:
var func = function () {
return this;
};
console.log(func.call('test'));
The console (at least FireBug) won't show us "test", but instead it shows String {0="t", 1="e", 2="s", 3="t" }. typeof would return "object".
The content of the this statement seems to need to be an object. In order to convert a string into a "String" object we can do console.log(new String('test'));, which is the same as the previously logged value.
To convert a string object into a string (data type), just use its prototype toString.

Categories