How to distinguish strings from ints in firebug console - javascript

I need to distinguish "0" from 0 in Firebug console.log output.
If you type console.log("0") into Firebug console, you'll get 0, same as if you'd typed console.log(0), but I need it to be "0".
In other words, expected output:
console.log("0")
> "0"
console.log(0)
> 0
Actual:
console.log("0")
> 0
console.log(0)
> 0
What is the best solution to this problem?
I've found some workarounds like console.log("%o", "0") or console.log(["0"]), but they are too clumsy and obtrusive to use them everywhere.
I've also tried debug and info without success.
By the way, Chrome console gets it right, but I'm not ready to move to Chrome yet.
I'm thinking about writing some wrapper around console object. I'm not sure how to do it right but I'll try it if there is no other solution.
So, the only solution seems to be that you need make some wrapper that looks like this (based on #wsanville's answer):
var log_orig = console.log;
// No need to check for type, just use %o for everything
// Also, it gets messier for multiple arguments
console.log = function(s) { log_orig('%o', s); }
But then you get the problem with line numbers, as described in How to access line numbers when wrapping Firebug (or similar) Console api
I guess I should file a firebug bug or something, because this can be really critical in some situations.

You could try using console.log(new String('0')) to distinguish from the two cases.
You could also just clobber console.log and encapsulate whichever solution you like best, like this:
var log_orig = console.log;
console.log = function(s)
{
if (s === '0')
log_orig('%o', s);
else
log_orig(s);
}
console.log('0'); //results in "0"

You could use:
console.log("Variable x type is " + typeof(x))
The typeof unary operator determines the type of the variable.
The return values are boolean, number, object, string, or undefined.

console.log(0) will show 0 but in darkblue color
console.log('0') will show 0 in black color
Also you could redefine console.log function:
var _log = console.log;
console.log = function(x) {
if ( Object.prototype.toString.call(x).indexOf('String') != -1 ) {
return _log("'"+x+"'");
} else {
return _log(x);
}
}

Related

Write function, which returns an unique identifier for parameter.(Java Script)

I have tried to do it, but all I get is that output: ---> Symbol(Test)
Is it even possible to get output like this(with single quotes in it): ---> Symbol('Test')
function getUnique(param) {
param = Symbol(param);
return param;
}
console.log(getUnique('Test')) // Symbol('Test') <--- I need to get that output
[Updated] Not sure if this is what you want...
function getUnique(param) {
param = Symbol("'" + param + "'");
return param;
}
console.log(getUnique('Test'))
The representation of what gets printed at the console is implementation dependent and could even vary from version to version of the same implementation. Running it in latest chrome gives an output of Symbol(Test) and firefox gives Symbol("Test"). It's the same thing either way: the console printed output is just a representation of the thing. It isn't actually any different, it's still a unique Symbol 'Test'.
I may be completely misunderstanding your question, but if you mean
Symbol('Test') <--- I need to get that output
You can append the single quote characters to the string like so:
const getUnique = (param) => {
const sym = Symbol(param);
return sym;
}
console.log(getUnique(`'test'`))

check if not undefined always evaluates to true

I have the following Javascript
var array = $('#calendar').fullCalendar('clientEvents');
var newArray = [];
array.forEach(function(entry) {
if (entry.description != undefined) {
newArray.push(entry);
}
});
I have an array filled with objects where some has a description and some does not - and I would like to filter out those that do not.
My problem is that the if-statement always evaluates to true no matter if description is undefined or not
As you can see from the screenshot - entry.description is undefined, but it still pushes it to the array.
What am I doing wrong?
Update
It seems to be working as intended with original code - after a firefox restart :S
I believe it might have been a firefox debugger issue.
Thank you all for you help anyway - feel free to comment on the actual code piece if you have anything to add though
Try this one:
if ( typeof entry.description != "undefined" ) {
//code if not undefined
}
try hasOwnProperty
if(entry.hasOwnProperty("description ")){
//you code
}

Screeps: write debug output to console?

Is there a way of getting screeps code to print strings to the console (or anywhere really) for simple debugging purposes?
You can use standard console.log method for that.
I use the following to print objects to the console:
console.log(JSON.stringify(<myVariable>))
I can't find how to do this in Docs. Had to write something like this:
module.exports = function () {
var log = Memory.log;
if(log === null || log === undefined){
log = Memory.log = [];
}
var parts = ["["+Game.time+"]"];
for(var i in arguments){
parts.push(arguments[i]);
}
var msg = parts.join(" ");
log.push(msg);
if(log.length > 10){
log.shift();
}
}
Will be grateful if someone can provide a better solution.
Sometimes when you do console.log you get unhelpful string representations of objects, something like like "[Object]".
If you want to drill down into the object and check out it's properties, the easiest solution is to open your browser's console. The devs made it so any console.log in your script will also reach the standard browser console. I believe it works in all major browsers.

Script debugger reports "operation not allowed"

I have a simple project that does some generic array calculations and returns the result in a grid. I needed a short way to scan an array for the maximum value and tried using this:
var max = Math.max.bind( Math.max );
var vector_max = Function.apply.bind( max, null );
Now, this works great when I am not debugging. But, if I wrap a test function around any statement, like, say:
function tester() {
var r = 0;
return r;
}
..., set a breakpoint anywhere in this function, and click debug, I get an error:
"Typeerror: This operation is not allowed. (line XXX, file xxx)"
This happens even in a completely new script attached to an empty sheet. Of course, Google has no documentation on their script debugger and no references to any limitations, so, I am totally in the dark.
Any ideas?
I can also reproduce this. It indeed seems like a bug in the debugger! :)
You should report this in the Apps Script issue tracker. And in the mean time use another implementation for your vector_max function to debug your code. For example:
function vector_max(a){ return a.reduce(function(r,v){ return r < v ? v : r; }, -Infinity); }

How to check null objects in jQuery

I'm using jQuery and I want to check the existence of an element in my page. I have written following code, but it's not working:
if($("#btext" + i) != null) {
//alert($("#btext" + i).text());
$("#btext" + i).text("Branch " + i);
}
How do I check the existence of the element?
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}
(Since I don't seem to have enough reputation to vote down the answer...)
Wolf wrote:
Calling length property on undefined
or a null object will cause IE and
webkit browsers to fail!
Instead try this:
// NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram
if($("#something") !== null){
// do something
}
or
// NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram
if($("#something") === null){
// don't do something
}
While it is true that calling the length property on an undefined or null object will cause browsers to fail, the result of jQuery's selectors (the $('...')) will never be null or undefined. Thus the code suggestions make no sense. Use one of the other answers, they make more sense.
(Update 2012) Because people look at code and this answer is pretty high up the list: For the last couple of years, I have been using this small plugin:
jQuery.fn['any'] = function() {
return (this.length > 0);
};
I think $('div').any() reads better than $('div').length, plus you won't suffer as much from typos: $('div').ayn() will give a runtime error, $('div').lenght will silently most likely always be falsy.
__
Edits november 2012:
1) Because people tend to look at code and not read what is said around the code, I added two big caveat lector notes to the quoted code of Wolf.
2) I added code of the small plugin I use for this situation.
The lookup function returns an array of matching elements. You could check if the length is zero. Note the change to only look up the elements once and reuse the results as needed.
var elem = $("#btext" + i);
if (elem.length != 0) {
elem.text("Branch " + i);
}
Also, have you tried just using the text function -- if no element exists, it will do nothing.
$("#btext" + i).text("Branch " + i);
jquery $() function always return non null value - mean elements matched you selector cretaria. If the element was not found it will return an empty array.
So your code will look something like this -
if ($("#btext" + i).length){
//alert($("#btext" + i).text());
$("#btext" + i).text("Branch " + i);
}
In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:
// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
for ( var name in obj ) {
return false;
}
return true;
}
Use it like:
console.log(isObjectEmpty(the_object)); // Returns true or false.
What about using "undefined"?
if (value != undefined){ // do stuff }
no matter what you selection is the function $() always returns a jQuery object so that cant be used to test. The best way yet (if not the only) is to use the size() function or the native length property as explained above.
if ( $('selector').size() ) {...}
if ( $('#whatever')[0] ) {...}
The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]
use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)
Using the length property you can do this.
jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) {
//do somthing
}
when the object is empty return this error:
Uncaught TypeError: Cannot read property '0' of null
I try this code :
try{
if ($("#btext" + i).length) {};
}catch(err){
if ($("#btext" + i).length) {
//working this code if the item, not NULL
}
}
if (typeof($("#btext" + i)) == 'object'){
$("#btext" + i).text("Branch " + i);
}
Calling length property on undefined or a null object will cause IE and webkit browsers to fail!
Instead try this:
if($("#something") !== null){
// do something
}
or
if($("#something") === null){
// don't do something
}

Categories

Resources