My issue is trying to pass a variable defined via prompt into an object method. At the end of my code I try to pass variable "house" into the ".teamPick" method in my class constructor but no-go. If I console.log(house) it prints 'gryffindor' but when I try to pass house.teamPick() I get an error saying "house.teamPick() is not a function." I am at my wit's end.
function House(color,broom) {
this.color= color;
this.broom= broom;
this.teamPick= function() {
alert("Throw on your"+" "+ this.color + " " + "robes, jump on your \n" + this.broom + ", " + "and let's play some Quidditch!")
};
};
var gryffindor= new House('red', 'Firebolt');
var house= prompt('What team do you choose?').toLowerCase();
if(house=== "gryffindor") {
house.teamPick();
};
You are using the wrong value (house) at the end of your script. house is a string value and not an instance of House.
gryffindor is an instance of House (created with new House()), so that's what you want to use instead.
You want the last three lines to be something like this:
if(house === "gryffindor") {
gryffindor.teamPick();
};
Related
I have the following code which works:
ctx.load(workflowAssociations);
//below works but loops through all available workflows, it seems sub may contain the array that needs to be accessed
ctx.executeQueryAsync(function (sender, args) {
var subsEnum = workflowAssociations.getEnumerator();
while (subsEnum.moveNext()) {
var sub = subsEnum.get_current();
alert(sub);
console.log('Web: ' + web.get_url() + ', Subscription: ' +
sub.get_name() + ', id: ' + sub.get_id());
var initiationParams = {};
workflowServicesManager.getWorkflowInstanceService().startWorkflowOnListItem(
sub, items.getItemAtIndex(0).get_id(), initiationParams);
ctx.executeQueryAsync(function (sender, args) {
console.log('Workflow started.');
}, errFunc);
}
}, errFunc);
function errFunc(sender, args) {
alert("Error occured! " + args.get_message() +
'\r\nStack trace: ' + args.get_stackTrace());
}
I am trying to simplify this loop and only access one object in the collection without the while loop. I have tried the following:
//var subsEnum = workflowAssociations.getEnumerator();
console.dir(subsEnum);
console.dir(workflowAssociations[2]);
console.log(subsEnum[2]);
var sub = subsEnum.get_current(0);
console.dir(sub);
console.dir(subsEnum);
However, most of these come up undefined. Here is an image of what it looks like when I explore the object using the watch expression ability in chrome.
I dont want to use that $2_0 thing because in migration I assume it may change.
I apologize in advance for any lack of information.
SP.Workflow.WorkflowAssociation class (workflowAssociations in your example) derives from SP.ClientObjectCollection class which in addition to getEnumerator() method contains some additional methods for accessing collection data such as:
getItemAtIndex - gets the element at the specified index of the SP.ClientObjectCollection class.
getData - transforms ClientObjectCollection object to regular JavaScript array
Examples
Enumerate collection
var e = workflowAssociations.getEnumerator();
while(e.moveNext()){
console.log(e.get_current().get_name()); //print Name of current WorkflowAssociation object
}
Get item at the specified index
var item = workflowAssociations.getItemAtIndex(0); //get first item
console.log(item.get_name()); //print Name of WorkflowAssociation object
Convert to array
var items = workflowAssociations.get_data();
console.log(items[0].get_name()); //print Name of first WorkflowAssociation object
Hey there I am searching for a function which is printing a dynamic variable as completely as possible to the console in Dart language.
In PHP for instance I would use var_dump() in order to get all information about a variable.
In JavaScript I would do one of the following:
1) Convert Object to JSON and print console.log(JSON.stringify(obj))
2) Or a custom function like this:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
However in Dart if I do print(variable) I get something like Instance of 'FooBarObject'. I cannot just convert an object to JSON like in JavaScript as this is not possible for all objects.
So my question in detail:
Is where a function or custom function in dart which can print a variable with unknown type (object, array, etc.) including all (public) properties as well as nested objects and variables to my console? Or which function is closest to this desire?
dart:developer library includes inspect function that allows debuggers to open an inspector on the object.
To use it add:
import 'dart:developer';
And then you can see your inspected variable/object in console with:
inspect(myVar);
There is no built in function that generates such an output.
print(variable) prints variable.toString() and Instance of 'FooBarObject' is the default implementation. You can override it in custom classes and print something different.
You can use reflection (https://www.dartlang.org/articles/libraries/reflection-with-mirrors) to build a function yourself that investigates all kinds of properties of an instance and prints it the way you want.
There is almost no limitation of what you can do and for debugging purposes it's definitely a fine option.
For production web application it should be avoided because it limits tree-shaking seriously and will cause the build output size to increase notable.
Flutter (mobile) doesn't support reflection at all.
You can also use one of the JSON serialization packages, that make it easy to add serialization to custom classes and then print the serialized value.
For example
https://pub.dartlang.org/packages/dson
I think there are others, but I don't know about (dis)advantages, because I usually roll my own using https://pub.dartlang.org/packages/source_gen
If it's a map then you can convert to JSON. First import convert package from flutter.
import 'dart:convert';
then convert to JSON and print
print(json.encode(yourMapVariable));
Update
Above answer is for map. For class / object add to toString() method.
Eg: say we have a user class
class User {
String name;
String address;
toString() {
return "name: " + name + ", address: " + address;
}
}
You can auto generate this toString() method using your IDE.
Simple little trick does the job
void printObject(Object object) {
// Encode your object and then decode your object to Map variable
Map jsonMapped = json.decode(json.encode(object));
// Using JsonEncoder for spacing
JsonEncoder encoder = new JsonEncoder.withIndent(' ');
// encode it to string
String prettyPrint = encoder.convert(jsonMapped);
// print or debugPrint your object
debugPrint(prettyPrint);
}
// To use simply pass your object to it
printObject(yourObject);
Instance of 'FooBarObject' This happens when you try to directly do print(object);
Even if you use convert package from flutter, it would throw Uncaught Error: Converting object to an encodable object failed:
To resolve this issue, first, make sure your model class or data class contains fromJson and toJson methods.
If you do so, your model class would look like this.
class User {
String name;
String gender;
int age;
User({this.name, this.gender, this.age});
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
gender = json['gender'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['gender'] = this.gender;
data['age'] = this.age;
return data;
}
}
And to print this as json import convert package
import 'dart:convert';
And call json.encode
//after initializing the user object
print('value is--> ' + json.encode(user);
Which will print the data as
value is--> {"name": "Vignesh","gender": "Male","age": 25}
use await keyword with an object in async function
void _registerUser() async { print(await form.result); }
If you want to know more about an instance of any class in an android studio click on a class name before variable then press ctrl+b it will take you to the class file where this object belongs from there you can see user attributes and methods of this class.
Try this one..
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
I'm writing a program (in JavaScript) that will determine the most suitable car based on a user's needs. I have 4 objects, each one a different car. For simplification purposes I will provide one object as an example. Assume there are 3 other objects with the same properties in my code (Fiat, Audi, BMW, etc.).
var chevy = {
make: "Chevy",
model: "Bel Air",
year: 1957,
color: "red",
passengers: 2,
convertible: false,
mileage: 1021
};
The goal is to pass each object as an argument to a function, and return a boolean value based on conditionals. Here is the function:
function prequal(car) {
if (car.mileage > 10000) {
return false;
}
else if (car.year > 1960) {
return false;
}
else {
return true;
}
}
And calling the function:
var worthALook = prequal(taxi);
if (worthALook) {
console.log("You gotta check out this " + taxi.make + " " + taxi.model);
}
else {
console.log("You should really pass on the " + taxi.make + " " + taxi.model);
}
Do I have to call each object seperately? Or is there a simplified way of calling the function for all 4 objects at once? I'm new to this and working through this problem spiked my curiosity.
Thanks!!
EDIT: Sorry for the rambling but I seem to have figured out a solution. I am getting the desired output by using a nested function:
function worthALook(car) {
var shouldYouBuy = prequal(car);
if (shouldYouBuy) {
console.log("You gotta check out this " + car.model);
}
else {
console.log("You should really pass on this " + car.model);
}
}
calling the original 'prequal' function (see above) inside the 'worthALook' function outputs:
You should really pass on this Taxi
You should really pass on this Cadillac
You gotta check out this Bel Air
You should really pass on this 500
After each object I called the worthALook function like so:
worthALook(chevy);
worthALook(fiat);
etc.
I received my desired output but does my code seem like overkill?
Thanks!
You could put the objects in an Array and filter what's worth a look. Return that object instead of a boolean.
function worthALook(){
return ([].filter.call(arguments, prequal) || [false])[0];
/* remove [0] from the above line and change [false] to false if you
want to return multiple cars that satisfy a condition. Use indexes if you do that */
}
var car = worthALook(chevy, fiat, audi, bmw); // pass inas many as you want
if(car) // check if it's a car
console.log("You gotta check out this " + taxi.make + " " + taxi.model);
The return statement is used with || so even if none of the cars satisfy the condition, then you could return false. Also, we are using arguments object, so you can pass in as many car objects to the worthALook function, which will make use of prequal function to filter 'em.
I am very new with Javascript and I can't seem to find an explanation for what is happening with my code.
I want to create an array of "people" where each person has some information associated with them, like "id" and "name". I don't know how many "people" I would need in my array so I am using "push" when I need another person. My problem is my array ends up filled with the last person's information.
Here is my declarations that I am using:
var ppl_arr = [];
var profile = {
id: 10000,
name: " ",
};
profile.id=3;
ppl_arr.push(profile); //add this person to my array
alert(ppl_arr[0].id + "\t" + ppl_arr.length);
profile.id=5;
ppl_arr.push(profile); // push next person to the array
alert(ppl_arr[0].id+"\t"+ppl_arr[1].id + "\t"+ppl_arr.length);
The first alert displays correctly : "3 1"
In the second alert, I get " 5 5 2" instead of " 3 5 2"
So I get two entries into my array but the second one seems to overwrite the first one. Can anyone explain what is happening?
You are simply changing the id of the same object, and adding the same object to the array twice. I would suggest that you create your 'people' objects as instance objects, something like this
//This is a constructor function for a Person object
function Person(id,name)
{
this.Id = id;
this.Name = name;
}
then
var ppl_arr = [];
ppl_arr.push(new Person(3,"Bob")); //add this person to my array
alert(ppl_arr[0].Id + " - " + ppl_arr.length); //outputs "3 - 1"
//NOTE put a string inbetween, because Id and length are both integers,
//you would actual get a sum of the two, not a string concatenation.
ppl_arr.push(new Person(5,"Steve")); // push next person to the array
alert(ppl_arr[0].Id+"\t"+ppl_arr[1].Id + "\t"+ppl_arr.length); // outputs 3 5 2
Question #1:
alert(ppl_arr[0].id + ppl_arr.length); will display the sum, not the concatenation - try alert(ppl_arr[0].id.toString().concat(ppl_arr.length));
Question #2:
You change the id property of an existing object, not copy it. So you change the id of the object already in the array as well. So you would need to
var ppl_arr = [];
var profile = {
id: 10000,
name: " ",
};
profile.id=3;
ppl_arr.push(profile);
//Create a new profile
var profile2 = {
id: 10000,
name: " ",
};
profile2.id=5;
ppl_arr.push(profile2);
I've got a .each loop that is processing an object returned from a JSON feed a la Ajax (Type: jsonp; success function sends the "data" to the function/method that contains the .each loop).
What's got me scratching my head is that, if the feed returns more than one set of data, it parses it out just fine. But if the feed returns only ONE set of data, the loop is trying to break out the individual fields of that lone record, as if each field were a record itself.
Here are examples of the object that comes in from the Ajax routine:
Example 1: -- single item
{
"SmeDetail": {
"SipAddress": "jane.smith#whatever.com",
"SubjectExpert": "Smith,Jane",
"SubjectMatter": "Unix"
}
}
Example 2: -- multiple items
{
"SmeDetail": [
{
"SipAddress": "fred.flintstone#whatever.com",
"SubjectExpert": "Flintstone,Fred",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "barney.rubble#whatever.com",
"SubjectExpert": "Rubble,Barney",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "wilma.flintstone#whatever.com",
"SubjectExpert": "Flintsone,Wilma",
"SubjectMatter": "Bedrock"
}
]
}
Now, here's the .each routine:
$.each(json_data.SmeDetail, function (i,val){
var sip_address = val.SipAddress;
var SME_name = val.SubjectExpert;
var subject_matter = val.SubjectMatter;
var sip_link = "<a href='sip:" + sip_address +
"'><img src='http://server/prod/images/im.gif' hspace='2' border='0' title='Send an instant message to " +
SME_name + "' alt='Send an instant message to " +
SME_name + "'/></a>";
output7 = output7 + "<tr><td>" +
SME_name + " " + sip_link + "</td></tr>";
});
I put some alert statements in there so I could verify the data. And when this runs for a single record coming back from the feed, it loops three times and assigns "undefined" to all of the variables. So, because it's looping exactly three times, plus the fact that it's entering the loop at all, tells me it sees a "SmeDetail" record, but it's treating each individual field as a record.
Makes me wonder if the structure of that return of a single record is correct? Should there be brackets around that lone item?
var detail = json_data.SmeDetail;
if (!detail.length) detail = [detail];
$.each(detail,....