Screeps: write debug output to console? - javascript

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.

Related

JS Error with for(var key of...)

I have some code that I have been using in an application for some time now where all of our internal users are using firefox for running the app. There are a few people wanting to run IE and there is a block of code that I believe is hitting an error and I don't know exactly why..
// Given a field name, check to see if its in our output. If so, return the formatted link
function createLink(field, val) {
var output = {
'ntid': 'https://web.internal/profile/' + val,
'email': 'mailTo:' + val
};
for (var key of Object.keys(output)){
if (field.toLowerCase().includes(key)){
return `${val}`;
}
}
return val;
}
In IE 11, I get a console error SCRIPT1004: Expected ';' which refers to the line for (var key of Object.keys(output)){.
Is this not supported in IE11 or is there some type of syntax that FF handles correctly that IE doesn't?
Instead of the "for...of", try a "for...in" which is supported by every browser for a long time now. Syntax is exactly the same.
(There is a difference between them but I guess in your case it's not relevant... More about this here: What is the difference between ( for... in ) and ( for... of ) in javascript? )
Instead of the "for...of", try a "for...in" which is supported by
every browser for a long time now. Syntax is exactly the same.
Not entirely:
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/for...of

object with array type string causing a typeError

The best way to explain this is just to show you.
var condition = 70;
var formnames = new Array("wheelcheckbox1", "wheelcheckbox2","spokecheckbox","spokecheckbox2","tirecheckbox","tirecheckbox2","tirecheckbox3");
formnames.forEach(function(entry) {
console.log(obj.entry);
if(obj.entry == "") {
condition = condition - 10;
}
});
as you can see I used the console log to show how it needs to work
as that works perfect, however, using the array causes an error as
they're strings and not what the obj wants, it wants text without it being a string.
Any ideas?
for..in should not be used to iterate over an array. Consider using forEach instead.

jQuery append fail in IE

I have this object that I would like to append to my div#doctors-list.
Firefox,Chrome work like a charm.But all IE fail. No errors are shown in the console.
$.each(sorteddoctorsArray[i2], function(idx, val) {
if ( !$.browser.msie ) {
$('div#doctors-list').append(val);
}else{
console.log(val);
// this logs [object Object]
$('div#doctors-list').append(val); // fails
}
});
any suggestions?
open it in IE and firefox to see the difference
try:
$('div#doctors-list').html($('div#doctors-list').html()+val);
It's hard to say when you disable the IE-Code(it currently is commented out).
But one issue I see so far(a few lines above the code posted by you) :
$('div#doctors-list').html('');
for(var i in priority){
for(var i2 in sorteddoctorsArray){
Both, priority and sorteddoctorsArray are native Arrays, you should never walk native Arrays by using for...in, always use for(var i=0;i<array.length;++i)
The for...in -Syntax will walk trough all members of an object. Also the build-in Array-members, e.g. length , will be fetched, what may result in errors.

How can I view an object with an alert() [duplicate]

This question already has answers here:
How can I display a JavaScript object?
(40 answers)
Closed 2 months ago.
I tried to do a debug but I am having problems. Now I try with alert(). For example I want to see the value of:
var product = { ProductName: $('!Answer_Response[0]').val(),
UnitPrice: $('#Price').val(),
Stock: $('#Stock').val()
};
When I say alert(product) it just gives me [object Object]. How can I make alert show what's really there?
you can use the JSON.stringify() method found in modern browsers and provided by json2.js.
var myObj = {"myProp":"Hello"};
alert (JSON.stringify(myObj)); // alerts {"myProp":"Hello"};
or
also check this library : http://devpro.it/JSON/files/JSON-js.html
you can use toSource method like this
alert(product.toSource());
If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log:
console.log(product);
If you want to view the properties of the object itself, don't alert the object, but its properties:
alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)
As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.
This is what I use:
var result = [];
for (var l in someObject){
if (someObject.hasOwnProperty(l){
result.push(l+': '+someObject[l]);
}
}
alert(result.join('\n'));
If you want to show nested objects too, you could use something recursive:
function alertObject(obj){
var result = [];
function traverse(obj){
for (var l in obj){
if (obj.hasOwnProperty(l)){
if (obj[l] instanceof Object){
result.push(l+'=>[object]');
traverse(obj[l]);
} else {
result.push(l+': '+obj[l]);
}
}
}
}
traverse(obj);
return result;
}
You should really use Firebug or Webkit's console for debugging. Then you can just do console.debug(product); and examine the object.
Try this:
alert(JSON.parse(product) );
Use Javascript native JSON.stringify method. To visualise it in a nicer way, you can use, like: JSON.stringify(obj,null, 4)
var obj = {data:[{"empmenuid":"1","empid":null,"deptid":"66","aliasid":"66","firstname":"66","lastname":"66","sin":"66","status":"66","empclass":"66","hiredate":"66","seneoritydate":"66","separationdate":"66"},{"empmenuid":"3","empid":null,"deptid":"12","aliasid":"12","firstname":"12","lastname":"12","sin":"12","status":"12","empclass":"12","hiredate":"12","seneoritydate":"12","separationdate":"12","recalldate":"12","martialstatus":"12","gender":"12","pager":"12","locid":"12","jobtitle":"12","jobtitlestart":"12","fullpart":"12","manager":"12","managername":"12","middlename":"12","nickname":"12","paytype":"12","payfreq":"12"}],
recordType : 'object'};
alert(JSON.stringify(obj,null, 4));
Depending on which property you are interested in:
alert(product.ProductName);
alert(product.UnitPrice);
alert(product.Stock);
alert( JSON.stringify(product) );
alert (product.UnitName + " " + product.UnitPrice + " " + product.Stock)
or else create a toString() method on your object and call
alert(product.toString())
But I have to agree with other posters - if it is debugging you're going for then firebug or F12 on IE9 or chrome and using console.log is the way to go

How to access key itself using javascript

I have a JSON like:
var xx = {'name':'alx','age':12};
Now I can read the value of name which is 'alx' as xx[0].name, but how should I retrieve value of 'name' itself? By that, I mean how can I fetch the key at run time?
for (i in xx) {
if (xx[i] == "alx") {
// i is the key
}
}
modified Code (from Victor) taking into account that you might want to look for any other possible string
var search_object = "string_to_look_for";
for (i in xx) {
if (xx[i] == search_object) {
// i is the key
alert(i+" is the key!!!"); // alert, to make clear which one
}
}
You are looking for associative arrays in Javascript. A quick google search suggests the following:
Read this page http://www.quirksmode.org/js/associative.html
and especially this section http://www.quirksmode.org/js/associative.html#link5

Categories

Resources