Strings not formatted in Node.js after a non-string - javascript

Is the following a bug or a feature in Node.js? If it is a feature, please point out at the spec.
When we call this:
console.log('one\ntwo', 'three\nfour');
we get the expected:
one
two three
four
But if we use a non-string value in front of it, then strings are no longer formatted as expected:
console.log(1, 'one\ntwo', 'three\nfour');
outputs:
1 'one\ntwo' 'three\nfour'
Why is that?
UPDATE
From the link by #MuliYulzary, it would appear that it is supposed to set the formatting, based on whether the first parameter is a string or not.
I found out, that when the first parameter is a string, Node.js uses util.format(parameters), and when the first parameter is not a string, it uses util.inspect.
That's how it works.

From the document console.log, it works correctly
console.log(object [, object, ...])
Logs a debug level message. You pass one or more objects to this method, each of which are evaluated and concatenated into a space-delimited string. The first parameter you pass to console.log() may contain Format Specifiers.
See the sample usage here

Related

getComputedStyle Font Family returns multiple families [duplicate]

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:
435,345,345345,56456
What I want to achieve is to get the first integer ie. 435 from the list.
I know how to do this in server side code but client side code.
Can someone please help me with this?
Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.
http://www.w3schools.com/jsref/jsref_split.asp
An Example
var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
alert(splitRowObject[0]);
alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.
One of the solutions you can do without knowing the structure is:
var firstInteger = +rowObject.toString().split(',')[0] // 435
That works if rowObject is string, array or everything else :).
EDIT: Putting + before the string will try to convert it to a number.
Have you tried rowObject[0]?
The fact that the alert shows 435,345,345345,56456 doesn't mean that the object is string, it could be Object and Array as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];

jquery console.log and alert different value

I realy cant understand javascript. Maybe someone can explain me the difference:
validationErrors[value.element.name] = value.method;
console.log(validationErrors);
alert(validationErrors);
console.log(validationErrors) returns well formed array with values, and alert(validationErrors) returns empty array. Why?
The console is more of a debugging environment and can understand the JS objects that are passed in the log function.
Alert on the other hand is a dialog box and will coerce its arguments into string values. Which is why the output is not as well formatted as the console.
Here is a little snippet of what is actually happening in the alert box.
var validationErrors = [ 2, 3, 4 ];
console.log(toString(validationErrors));
Output >> "[object Window]"
It's also best practice to use the console for logging purposes and not the alert box.
you can try this
alert(JSON.stringify(validationErrors));
Alert have some limit according to browser it varies but most You'd probably be best staying under 1000 characters though, as many browsers seem to begin to truncate after 999.
And if you are giving object in alert it will never reflect the values so prefer console for object and other data type can be used in alert but its not a good practice.
console give proper view of data like object in array can be studied easily in console.
Alert is used to print messages, which means it is used to display string values. When you pass anything other than string to alert, it calls .toString function of it and prints the output.
Now why did you get a blank string?
An array is supposed to have indexed values only. So you can do array[index] = "bla bla". But when you do array["something"] = "something else", it adds a property to that array (since arrays are also objects in Javascript).
According to MDN
The toString() method returns a string representing the specified array and its elements.
In simple, it will loop over length of array and join all elements with ,(comma)
But you do not have elements in it. You have set properties. So length is 0 and hence it returns ""
Following is a simulation
var a = [];
a["test"] = "foo";
console.log(a);
console.log(a.toString());
alert({})
Reference
Alert
Array.prototype.toString
All objects in Javascript are passed by reference. So when you passed something to console.log() and it would be changed in code further, in console you will see changed value. On other hand, alert() displays message box and stops code execution, so in message box you see values exactly as they are at alert()'s call time.
For debugging purposes, you may want to use browser's debugger - I recommend Chrome Dev tools. There is free course from codeschool.com to help you discover such great tool: https://www.codeschool.com/courses/discover-devtools

How can I debug my data in conosle?

I have some react code that renders various panels in the UI.
I'm trying to debug, but when I use console statements to show sportsTopBar.propTypes, for example, it prints [object Object]. When I use JSON.stringify it prints empty.
So how can I debug my structures in the console?
Code snippet provided below. The code can be seen in its entirety in the fiddle.
code snippet
sportsTopBar.propTypes = {
sports-layout: React.PropTypes.string.isRequired,
sportsPanelState: React.PropTypes.object.isRequired,
sports: React.PropTypes.object.isRequired
};
console.log("sportsTopBar.propTypes--->" + sportsTopBar.propTypes);
console.log("sportsTopBar.propTypes--->" + JSON.stringify(sportsTopBar.propTypes));
output
sportsTopBar.propTypes--->[object Object]
sportsTopBar.propTypes--->{}
Problem 1
Syntax error
sports-layout: should be "sports-layout":
Problem 2
You're implicitly casting to string
Your comment on this answer made me realize what all this is about. You want to see what this object looks like in the console, and can't get it to output as expected. So, this line:
console.log("sportsTopBar.propTypes--->" + sportsTopBar.propTypes);
Has the problem of using + to concat the leading string to the value you're wanting to see in the console. This concatentation is causing an implicit cast to string of your object, thus the output of [object Object] where you expected to see the actual object. [object Object] is the toString output of an object.
So to get these logged together in the same output, you need to take advantage of console.log's allowance for multiple parameters:
console.log("sportsTopBar.propTypes--->", sportsTopBar.propTypes);
Notice that what I've done is replace the + with ,. Each will now be logged as given, with no casting done on them.
Problem 3
JSON cannot represent functions
Per JSON.org:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
I assume that React.PropTypes.string.isRequired is a function. As such, the serialized output of any object with a property that references that function will not contain a representation of that property/method. Further, your object contains only references to that function, so the resulting serialization (after functions are stripped) is the representation of an empty object: {}.

JQuery: parameter: hard-coded string vs ajax retrieved string

I am trying to get the JQuery Token Input prepopulated.
var assignUserJson=$('#assignUserJson').val();
console.log(assignUserJson); //[{"id":"1","name":"Andrew"},{"id":"3","name":"John"}]
Here is a difference between two ways that I supposed it should work in:
$('#assignTask').tokenInput('/users/suggest', {prePopulate: assignUserJson}); // doesn't work
And this works:
$('#assignTask').tokenInput('/users/suggest', {prePopulate: [{"id":"1","name":"Andrew"},{"id":"3","name":"John"}]}); // works
Why is that? Shouldn't I be able to get the value from a hidden input field and pass it to the tokenInput function?
In your first method, assignUserJson is a string whereas in the second method, it is an array object. Objectifying the first one should work:
$('#assignTask').tokenInput('/users/suggest', {prePopulate: JSON.parse(assignUserJson)});
With the first method you're passing a JSON string, not a tangible JS object as you are in the second.
You would first need to parse the JSON. This can be done natively in ECMA5 or, for older browsers, via third-party support.
$('#assignTask').tokenInput('/users/suggest', {prePopulate: JSON.parse(assignUserJson)}); // doesn't work

How to print an object on the developer tools console in Javascript

Please help me in printing the complete object using console.log method. If I am simply putting the name of the object it simply prints [object] [object]. But I want to print the object with complete hierarchy.
For an example, I am getting object in the following method,
getObject : function(responseObj) {
console.log('Object hierarchy is'+responseObj)
}
This simply returns [object] but I want to see the complete hierarchy in the developer tools. Please see, I am using sencha.
Use console.dir, and don't concatenate...
console.dir( responseObj );
Or if you want a label, use a comma to pass multiple arguments.
console.log('Object hierarchy is:', responseObj)
The problem here is that you are concatenating an object onto a string, so it's not doing what you are expecting. Instead of putting it all into one console.log call, do two, the first with the text you want, and the second with just the name of the object in it.
getObject : function(responseObj) {
console.log('Object hierarchy is:');
console.log(responseObj);
}
edit:
If you are logging into a text/non-interactive console, that doesnt let you explore the object, you'll need to implement a custom inspection function, something like this gist will get you started. What this is doing is echoing out the property name, and the value it finds step by step, but pay attention to what it says there about scoping.
edit edit:
didn't know about console.log taking multiple parameters, never needed it :o handy though!

Categories

Resources