I am setting an object like this
n.name = n.name.join(String.fromCharCode(255));
n.description = n.description.join(String.fromCharCode(255));
I want to be able to alert(n); but it tells me [Object]
is there a way to alert complete object?
thanks
Javascript supports adding a toString() function to your objects. This will get called when you alert your object. For example:
n.toString = function(){
return this.name + '\n' + this.description;
}
then alert(n); will display whatever content your function specifies.
I was asking the same kind of question as Autolycus today. I'm using jqGrid and I wanted to see what the object it created actually was. I didn't create the object and I wanted to see what it looked like. I know it's probably old school, but I still use alerts in javascript for some of my debugging (though I agree FireFox & Firebug are the way to go for most things).
I found an answer to what I was looking for here: http://javascript.internet.com/debug-guide.html, which is unbelievably old.
But I tweaked it to give me what I needed and since I think it answers Autolycus's question in a new way and I think someone else might be looking here, like me, for this someday, here it is:
obj = n;
var temp = "";
for (x in obj) {
temp += x + ": " + obj[x] + "\n";
}
alert (temp);
I apologize in advance if answering an old question is breaking some kind of rule.
all best,
ember
I like the var_dump in php, so I often use a function like this to dump variables
function var_dump(object, returnString)
{
var returning = '';
for(var element in object)
{
var elem = object[element];
if(typeof elem == 'object')
{
elem = var_dump(object[element], true);
}
returning += element + ': ' + elem + '\n';
}
if(returning == '')
{
returning = 'Empty object';
}
if(returnString === true)
{
return returning;
}
alert(returning);
}
There are a couple of alternatives:
1. Use http://www.gscottolson.com/blackbirdjs/
2. Use console.log() that comes with Firebug, but requires Firefox (even if you only target only IEs, it's still wise to use Firefox and Firebug as aprt of testing of your web app development)
It depends what you mean by alerting the complete object.
You can't really just output every object as a string and have it make sense. To define how an object will display itself as a string we use the .toString(); method.
So try alert(n.toString()); and see if that will give you what you want. If the object is your own, then define the toString(); and have it return a string of the parameters and fields that you want to output.
Something like...
alert(n.name);
...I think is what you want.
If you are trying to debug, you would be better suited to using FireFox/Firebug instead of inserting a load of alerts();
Related
Is there a method or way in JavaScript that I can check if assert if a function returns a value through the use of an if statement?
So this:
function(val) {
if (val) return "it is true";
return "it is false";
}
versus this:
function(val) {
var str = 'it is ';
return str += val;
}
I've been looking around and can only find articles related to Java or other languages. Thanks in advance.
EDIT: I'm writing tests to assert whether or not a function (written by a user) utilizes an if statement. Hope that clarifies that a bit!
First I'd like to mention that such checks shouldn't be used in code, in which I mean that proper code should never check whether an if-statement is used inside a function. Whether a value is returned from it or not, this shouldn't be checked or tested.
But, to get back on topic. I'm not quite sure whether this is possible out of the box. I do however have a solution that you might be able to use to achieve something similar to your goals.
You can convert a given function to it's string representation. Take a look at the following example:
// Define a function
var myFunction = function() {
return 1 + 3;
};
// Print the function, as a string
console.log(myFunction.toString());
This code will print the string representation of the function in the console, so that will be function() { return 1 + 3; }. Some environments, such as the Firefox return a compiled version of the function which would look like function() { return 4; } but that doens't really have any effect on our use.
Using this method you'll be able to check whether the given function contains an if-statement. Such code would look like this:
// Define a function
var myFunction = function() {
return 1 + 3;
};
// Check whether the given function contains an if-statement
if(myFunction.toString().indexOf('if') > -1) {
console.log('This function does contain an if-statement');
} else {
console.log('This function does not contain an if-statement');
}
This method isn't ideal for your situation but it might point you in the right direction. Please note that this method isn't a rock-solid solution, at least not in this state. The usage of 'if' as a string (or something else) in a function would also cause the code above to say that the function contains an if-statement. Also, this doesn't explicitly check whether a value is returned from inside of an if-statement.
If you'd like to ensure the things mentioned above (that a real if-statement is used, in which a value is returned from it) you might have to modify the above code to make it smarter if this string-based method suits your needs. Then, I'd highly recommend to write a fancy wrapper around it to make it easier in use.
I have a existing application which uses javascript and properties like notNull, isDate etc defined within the elements in html elements like input, select, etc
For example:
<input type = 'text' notNull class='mandatoryField' name = 'abc' id='abc' isDate/>
And the javascript checks for the properties with a hasProp method, placing the code below and corresponding warning messages are displayed:
function hasProp(thisField, thisProp) {
for ( var prop in thisField) {
if (prop == thisProp)
return true;
}
return false;
}
My issue here is with using different browsers - IE, Chrome and Firefox
This particular methods are all ok for Internet Explorer. when it comes to chrome and firefox, the notNull, isDate are treated as attributes rather than properties and the above hasProp method always returns false.
I did go through many questions available here, but couldn't find any way to access both properties and attributes in a single way - I would prefer jQuery to be used, since we will be migrating to jQuery eventually.
Any pointers to this will be really helpful.
Thanks,
Reema
I think the way you use the attribute and property aren't 100% accurate, properties (.prop()) in the jQuery context are basically the value of the attribute in memory, where as .attr() reflects the value in the markup. This is only the case for HTML attributes that are "built-in".
So in your example, you're dealing with attributes all the way, just some don't happen to have any value.
The best way of detecting the presence of an attribute, cross browser using jQuery:
$('#myElement').is('[attrName]') === true
So, in your case:
$('#abc').is('[isDate]') === true
See this JS-Fiddle
As you want a jQuery solution, you can use both jQuery.attr() and jQuery.prop() methods to solve your problem.
I would prefer an pure Javascript approach:
var attributes = ['notNull', 'isDate'],
checkForAttribute = function(elem){
for(var i = 0, c = attributes.length ; i < c ; i++){
if(elem.getAttribute(attributes[i]) !== null){
console.log("attribute " + attributes[i] + " found");
}else{
console.log("attribute " + attributes[i] + " not found");
}
}
}
See an working example here.
Here is some more information on the getAttribute() method.
How is it possible, that the browser can refresh the input element (or any other element), when I assign the value without a setter method, but just by normal assignment:
<script type="text/javascript">
document.getElementById("element_id").value = 'value';
</script>
Is there a native event, or is this a Javascript event? I would expect something like:
function setAttribute(value) {
model.value = ...
fireEvent();
}
But I can also set the attribute only without setter.
So where is this "event" fired (hidden somewhere in the assignment with '=') so that the browser knows that a refresh is needed?
Greetings
The JS engine is free to detect this however it wants. It could be a simple if (dest instanceof DOMElement) { special handling } or it could be an extremely complex process. It's just a simple assignment in JS land. In implementation land, it can do anything it wants as long as the end effect is correct.
In other words, it just looks like a simple assignment. Behind the scenes, it is most certainly more.
In Javascript you can have custom getters and setters for object properties:
var obj = {
get prop () { alert("Getting prop!"); return 4; }
set prop (newValue) { alert("Setting prop to " + newValue); }
}
obj.prop = obj.prop + 1;
So here, the last line triggers both alerts.
Like Corbin says, the actual JS/DOM implementation of the browser can do whatever it wants. Javascript is text that is interpreted (or compiled) into something that runs in a virtual machine. What the text means, and what effects it has when interpreted - is up to the interpreter.
It's late and silly-time, so to demonstrate, a very lousy "parser/interpreter" written in javascript... It only allows one kind of statement and has no syntax checking (or much of anything else). But who knows - it still might give a (very simplified) idea of what's going on when the browser interprets an actual script:
var myscript1 = "value = 3";
var myscript2 = "othervalue = 5";
var variables = {};
// Hey ho, let's run our two "scripts":
parser(myscript1);
parser(myscript2);
function parser(script)
{
// Super-simple lexer:
var tokens = script.split(" ");
// Rudimentary error checking:
if (tokens.length != 3 || tokens[1] != "=")
{
alert("syntax error!");
}
var variable = tokens[0];
var value = parseInt(tokens[2], 10);
// Execute our only allowed operation:
setVariable(variable, value);
}
function setVariable(name, value)
{
// Store our value (e.g. for later use in our script - if our interpreter
// actually allowed doing anything except assigning values to variables:
variables[name] = value;
// ... and do something with it:
alert(name + " was set to " + value + "!");
}
Our "language" doesn't have function calls or events, but our "interpreter" can do whatever it wants with the "scripts" given to it. As Corbin said, it looks like simple assignment, but behind the scenes (in the setVariable function), it is most certainly more (well, in this case, a bit more - triggering an alert).
I have a mystery object in Javascript - please could someone tell me how to initialise a similar object?
Background: I've inherited some code that gets passed a params object from Flash. I want to 'fake' the same call, which requires manually constructing the same object. But I can't work out how to take it, because I don't know what type of object it is. (It's not the content that's the problem: it's how to initialise the object.)
Please could someone tell me whether the params object following is an array, a list, a hash or something else - or at least how I can work it out for myself, given that there is no typeof in JavaScript?
function doSomething(params) {
var txt;
for (p in params) {
txt = txt + "param:" + p + ", " + params[p] + "\n";
}
return txt;
}
Thanks!
This will alert the type of 'params'.
function doSomething(params) {
alert("Type of params variable: " + typeof params);
var txt = '', p;
for (p in params) {
txt += "param:" + p + ", " + params[p] + "\n";
}
return txt;
}
If you just want to intercept the variable, and pass the param to the original function, try this:
window.originalFunction = doSomething;
window.doSomething = function(param1){
// do something with param1
return window.originalFunction(param1);
};
To check whether params is an array or not, try:
alert(params instanceof Array);
You can think of it as a hash. In your example, p is the property name and params[p] accesses the value of that named property.
And, as usual, Pekka is right. There most definitely is a "typeof" operator in Javascript. I don't know where you got the idea that there isn't.
From the looks of it, params looks like a dictionary
There are no lists, hashes, dictionaries (etc.) in JavaScript. There are only objects and arrays (and arrays are a type of object).
Given that the code uses for... in, it looks like it would be an Object. That is, a container with named members. Beyond that, it depends on how the object was initialized.
If you would like to make a copy of the object, try using its prototype:
var copy = {};
copy.prototype = params
The main issue I'm thinking about is whether assigning a variable in an if statement is safe and reliable across different browsers. If it is safe, I'd like to use it.
Here it reads the querystring and if the querystring variable SN is either Twitter or Facebook then it enters the if and you can use the variable, if the querystring variable doesn't exist or is some other value then it goes into the else.
if(socialNetwork = (window.location.search.indexOf("SN=Twitter") > 0) ? "Twitter" : ((window.location.search.indexOf("SN=Facebook") > 0) ? "Facebook" : null))
{
alert(socialNetwork);
}
else
{
alert("nope");
}
It is part of the language design and should work in every browser, but it's very difficult to read.
That's ugly.
var uselessSocialNetworkingApp = window.location.search.replace(/.*\bSN=(\w+)\b.*/, "$1");
if (uselessSocialNetworkingApp)
alert("yay!");
else
alert("no");
It's kind-of funny that there'd be that hideous construction in the "if" header, but that it'd be an "if" instead of a "? :" expression inside the "alert" argument list :-)
Also, to be at least slightly sympathetic to the intended style, this is an example of what the "let" statement in ultra-modern Javascript is for.
Oh my! This is valid and should always work, assuming that you create the socialNetwork variable elsewhere, don't ever create implied globals. However, this is really a strange way to solve your problem. Why not create a function that returns the social network to abstract this a little?
That said, if you really want a one line solution, how about this?:
alert(function(){ var m = /SN=([A-Za-z]+)/.exec(window.location.search); return (m ? m[1] : null)}());
location.socialNetwork== (function(){
var s= location.search || '';
s= /SN=([a-zA-Z]+)/.exec(s) || [];
return s[1] || null;
})()
alert(location.socialNetwork)