How can I access a property within a "if" statement? - javascript

Here is my block of code,obviously quite simple. Learning by myself but getting there!I'm trying to figure out how to compare two objects that I created out of my constructor. But I don't get the function to work. I'm not sure how to trigger the property within objects. Am I missing a fundamental knowledge here?
Don't want to sound cheezy, but thank you everyone for sharing and helping others-humanity. There's so much info available, and that is because of you. The ultimate goal of knowledge, is to share it.
function rectangle (length,breadth,colour){
this.length= length;
this.breadth= breadth;
this.colour= colour;
this.area= function(){
return this.length * this.breadth;
} /**The property (area) value is a function.**/
}
var Rectangle1 = new rectangle (5,3.5,"Green");
var Rectangle2 = new rectangle (7, 5.5, "Green");
function compareRectangles (Rectangle1, Rectangle2){
/**How can I target the property "area" within 'if' statement? or Did I get it all wrong?**/
if (Rectangle1 > Rectangle2){
return console.log(Rectangle1 + " is greater than Rectangle2 ");
}
else if (Rectangle1 < Rectangle2) {
return console.log(Rectangle2 + "is greater than Rectangle1");
}
else {
return console.log("They're same size");
}
}
compareRectangles(Rectangle1, Rectangle2);

Consider the following (added extra comments for your learning experience):
// capitalized Rectangle here to indicate it's a class (convention)
function Rectangle (length,breadth,colour){
this.length = length;
this.breadth = breadth;
this.colour = colour;
// removed quotes around area here
this.area = function () {
return this.length * this.breadth;
}
// removed the ; after the } as it's not necessary after function declarations
}
// renamed Rectangle to rectangle1 to align with what you use in the function
// also lowercased the variables because they're instances of a class and not the class constructor itself
function compareRectangles (rectangle1, rectangle2){
// check the .area method of the rectangle
// you can access properties and methods through a dot
// since area is a function, you need to execute with () to get the return value
if (rectangle1.area() > rectangle2.area()){
// changed console logs to not use the instance in the log.
// Since the instance is an object it would try to parse it as a string, resulting in showing [Object object] or something like that
// if you do want to log the rectangle, you should probably split that by adding an argument:
// console.log("the greater rectangle is:", rectangle1);
console.log("Rectangle1 is greater than Rectangle2");
// I changed your return value, since console.log returns nothing
// I figured it would be more relevant to return the 'winning' rectangle
return rectangle1;
}
else if (rectangle1.area() < rectangle2.area()) {
console.log("rectangle2 is greater than rectangle1");
return rectangle2;
}
else {
console.log("They're same size");
// no winning rectangle makes it return null, so you can recognize it when calling the function
return null;
}
}
// Removed capitals for the variables as they are not class constructors but instances of the class.
// Also changed this to let instead of var,
// you may want to read up on const/let and try to forget about the existence of var
// Currently these could be const since they are never reassigned, but I can imagine it is easier for you currently to stick to let instead
let rectangle1 = new Rectangle (5,3.5,"Green");
let rectangle2 = new Rectangle (7, 5.5, "Green");
// you'll need to 'send over' the rectangles that you're expecting in your function
let returnedValue = compareRectangles(rectangle1, rectangle2);
console.log('Received return value:', returnedValue);

When comparing their area property, use
Rectangle1.area(); //Notice the (), because you wanted to call that function in the...
Rectangle2.area(); //...code
Simply using Rectangle1 > Rectangle2 will compare them as objects. These themselves cannot normally be compared via > and <. You need to compare them with some of their property, which I know you are trying to do. But look at your code.
if (Rectangle1 > Rectangle2){
return console.log(Rectangle1 + " is greater than Rectangle ");
}
You only put Rectangle1 in the left-hand side of the operator. That is an object. To access its property, for example, length, you use Rectangle1.length
So do the same to access the function area, Rectangle1.area, thus call the function via Rectangle1.area().
if (Rectangle1.area() > Rectangle2.area()){
return console.log(Rectangle1 + " is greater than Rectangle2 ");
}
Essentially, just use the syntax:
object.property

Since the property is a function, you have to call it Rectangle1.area()
Also, you have to call the compareRectangles() function and pass the two rectangles you made:
function rectangle (length,breadth,colour){
this.length = length;
this.breadth = breadth;
this.colour = colour;
this.area = function(){
return this.length * this.breadth;
}
};
function compareRectangles(r1, r2){
if (r1.area() > r2.area()){
return console.log("Rectangle 1 is greater than Rectangle 2");
} else if (r1.area() < r2.area()) {
return console.log("Rectangle 2 is greater than Rectangle 1");
} else {
return console.log("They're same size");
}
};
var Rectangle1 = new rectangle (5,3.5,"Green");
var Rectangle2 = new rectangle (7, 5.5, "Green");
compareRectangles(Rectangle1, Rectangle2)
Output:
Rectangle 2 is greater than Rectangle 1

You simply have to call the area() method on the object to get the value
function compareRectangles (Rectangle1, Rectangle2){
if (Rectangle1.area() > Rectangle2.area()){
return console.log("Rectangle1 is greater than Rectangle2");
}
else if (Rectangle1.area() < Rectangle2.area()) {
return console.log("Rectangle2 is greater than Rectangle1");
}
else {
return console.log("They're same size");
}
}
call the function with required arguments
compareRectangles(Rectangle1, Rectangle2);
(Your question is improved. Please, go through your question to see miskates you made)

Related

Reset the amended values in the Else part of an if/else statement by removing the function

Is there an equivalent in JS of the initial value in CSS. When you have a function that you want to behave in a certain way with an if statement but, then in the else part you want the values to just be what they they were before the if piece of code returned true. I've always re-written the original values as part of the else, but this seems to be a galatically inefficient way of doing things, for example:
var a = something, b = something_else;
if (a) {
run a function which changes lots of values;
} else {
re-type the values to what they were before the function ran;
}
A more concrete version of what I'm trying to do is below. I have a forEach method that changes some string values. If I want to set it so that on the else all the code in the initial if is ignored I know I can do this by copy and pasting the code under a different function name and setting the second slice value to 300, which is the length of the original strings, but this seems a very verbose way of doing things?
There must be a way of setting the else code so it removes / kills off the original myresize() function so all the original values hold true?
var content = document.querySelectorAll(".generic-content p");
function textSlice() {
if (window.innerWidth < 500) {
function myresize() {
content.forEach(function(index) {
var x2, x3, x4;
x2 = index.textContent;
x3 = x2.slice(0, 100) + "[...]";
index.textContent = x3;
});
myresize();
}
} else {
// remove the myresize(); function or somehow kill it
}
}
addEventListener("resize", textSlice, false);
There is no built-in feature in JavaScript that restores the initial state of the elements. However, it is relatively easy to build such a feature. Before you start, save the state to a global object, which you can then use to restore the initial state whenever you want.
Try the code below. Note that the first parameter of the forEach method is the element itself, not the index. So it isn't right to name it index. I've changed it to item.
var content = document.querySelectorAll(".generic-content p");
//Save the initial state.
var initial = [];
(function() {
content.forEach(function(item) {
initial.push(item.textContent);
});
})();
function textSlice() {
if (window.innerWidth < 500) {
content.forEach(function(item) {
var x2, x3, x4;
x2 = item.textContent;
x3 = x2.slice(0, 100) + "[...]";
item.textContent = x3;
});
} else {
//Restore the initial state.
content.forEach(function(item, index) {
item.textContent = initial[index];
});
}
}
addEventListener("resize", textSlice, false);
<div class="generic-content">
<h4>Window Resize Demo</h4>
<p>first paragraph</p>
<p>second paragraph</p>
<p>third paragraph</p>
</div>

JavaScript default constructor| array | loops

I need to make a script but I have no idea how to complete it.
This is what I have to do:
(1) Write a class Boxes. this class has a default constructor and an empty array named boxes.
further has this class 3 methods:
1) insert add method to put Box into the boxes-array.
2) insert method size to get the actual size of the array.
3) insert toString method which give color and volume back in one string.
(2) continue in the init function:
2.3 turn a loop around every object from the array objects to add it to the array boxes
2.4 make a toString method to give back every object from your array in one HTML P-tag.
I hope this makes sense to you guys and it would be a big help if somebody could help me!
A big thanks in advance!
Update: I have edited the code to what I have now.
window.addEventListener("load", init, false);
function init() {
// (2.1)
let object1 = new Box(20, 8, 3, "white");
let object2 = new Box(30, 20, 10, "Brown");
let object3 = new Box(50, 40, 20);
// (2.2)
let boxes = new Boxes();
// (2.3)
boxes.push(object1);
boxes.push(object2);
boxes.push(object3);
// 2.4
var str=""
for (let i = 0 ; i < boxes.size() ; i++){
str += "<p>"+boxes.toString(i)+"<p>"
}
}
class Box {
constructor(length, width, height, color = "blue") {
this.length = length;
this.width = width;
this.heigt = height;
this.color = color;
}
volume() {
return this.length * this.width * this.height;
}
toString() { // String templates
return `Volume: ${this.volume()} --- Kleur: ${this.color}`;
}
}
// (1) class Boxes
class Boxes {
constructor(){
this.boxes = [];
}
add(Box){
this.boxes.push(Box);
}
size(){
return this.boxes.length;
}
toString(i){
this.boxes[i].toString();
}
}
I don't quite get what's 3) means so I would assume that you want to get the box color and volume given the index (correct me if I'm wrong)
class Boxes{
//init property called boxes to an empty array when creating Boxes object
constructor(){
this.boxes = [];
}
//return the length of the boxes
size(){
return this.boxes.length;
}
//add a box by pushing it to the array
add(box){
this.boxes.push(box);
}
//print the volume and color of a box given the index
toString(i){
this.boxes[i].toString();
}
}
for number 2:
//2.3
//do you have to push the objects to object?
//use this if you don't have to
boxes.push(object1);
boxes.push(object2);
boxes.push(object3);
//use this if you pushed your objects into an array called object
objects.forEach(function(singleObject){
boxes.push(singleObject);
});
//2.4
//Iterate every object in boxes and print out their volume and color
//Do you have to create a P tag or just wrapped the string with <p></p>?
//This answer assumes that you just wrap it with <p></p>. Correct me if I'm wrong
var str = "";
//option 1 Using foreach loop
boxes.boxes.forEach((singleBox){
str += "<p>"+singleBox.toString()+"</p>";
});
//option 2 Using for loop
for(var i = 0; i < boxes.size(); i++){
str += "<p>"+boxes.toString(i)+"</p>";
}
//now str contains every object's color and volume wrapped in P tag
I would recommend you to go through this course https://www.codecademy.com/learn/javascript

Javascript, console.log prints prints object, but property is undefined

And I have a function that reads in level data. This is the snippet in question; actors is an array and I'm looping over it until i find an actor of type player.
function Level(plan) {
//Cut snippet..........
this.player = this.actors.filter(function(actor) {
return actor.type == "player";
});
console.log(this.player);
//................
}
The player object,
function Player(pos) {
this.pos = pos
this.size = new Vector(0.8, 1.5);
this.speed = new Vector(0, 0);
}
Player.prototype = new Actor();
Player.prototype.type = "player"
The issue is that in the console, the
console.log(this.player)
will show all the correct details, but when i try to log the position for example
console.log(this.player.pos)
I get undefined. Its a simple program, I'm not using ajax or anything. Thought it might be do with execution order, can someone explain this to me and a solution? If it is todo with execution order, an explanation would be much appreciated.
Thank you very much,
Rainy
You get undefined because when you filter your actor array, you get a new array as a result. So console.log(this.player) outputs an array, not a single object.
You need to get the first element of the array this.player to output its pos property.
Something like this:
if(this.player.length > 0)
console.log(this.player[0].pos);
Use reduce instead of filter for a single player.
this.player = this.actors.reduce(function(current, actor) {
return actor.type === 'player' ? actor : current;
});

Issue with for loop and if statements in javascript

I am using Javascript and Openlayers library in order to style a vector feature on the map.
I have written the following script:
var gidS = response[Object.keys(response)[Object.keys(response).length - 1]] // get the data from json obj
// ADD STYLING - DIFFERENT COLORS FOR WHAT IS COMPLETE
var styleContext = {
getColor: function (feature) {
var objectKeys = Object.keys(gidS); // use objectkeys to loop over all the object properties //use it to get the length
for (var i = 0; i < objectKeys.length; i++){
//alert(i);
//////////////////
if(gidS[i][1]=="MT"){
//alert(gidS[i][1]);
return "green";
}
else if(gidS[i][1]=="IRU"){
alert(gidS[i][1]);
return "#780000"; //no images on this line
}
///////////////////////
}
}
};
If I run the script without the if conditions (between the slashes) then I get a correct incremental value of i based on the maximum length of gidS.
But when I include the if statements for some reason the variable i doesn't increment. It remains 0.
EDITED
The getColor function is executed later like this
// define Style
var defaultStyle = new OpenLayers.Style({
fillColor: "${getColor}",
fillOpacity:"1",
strokeColor: "${getColor}",
strokeOpacity: "1",
strokeWidth: 8,
cursor: "pointer",
pointRadius: 8
}, {
context: styleContext
});
What am I doing wrong here?
Thanks a lot.
D.
Capture the color in a variable, for example: color, and return it at the end of the function:
getColor: function (feature) {
var color = '';
var objectKeys = Object.keys(gidS); // use objectkeys to loop over all the object properties //use it to get the length
for (var i = 0; i < objectKeys.length; i++){
if(gidS[i][1]=="MT"){
color = "green";
}
else if(gidS[i][1]=="IRU"){
color = "#780000"; //no images on this line
}
}
return color;
}
By looping through every property of the object, and then returning, you're effectively getting the last possible matching "MT" or "IRU", if any. If you return out of the function as soon as you find a match, then your getting the first possible matching "MT" or "IRU".
For example, given the set: [[435,'IRU'],[34324,'MT'],[343,'MT']] My method will return green, and your method will return #780000.
don't use the return, it immediately stop after used .
try this altough i dont know the gidS.
if(gidS[i][1]=="MT"){
gidS[i]['color']='green';
}
else if(gidS[i][1]=="IRU"){
gidS[i]['color']='#780000';
}

How to set a dynamically generated pseudoclass name in JavaScript to work with the instanceof operator?

I'd like to set the name of a JavaScript pseudoclass stored in an array with a specific name, for example, the non-array version works flawlessly:
var Working = new Array();
Working = new Function('arg', 'this.Arg = arg;');
Working.prototype.constructor = Working;
var instw = new Working('test');
document.write(instw.Arg);
document.write('<BR />');
document.write((instw instanceof Working).toString());
Output:
test
true
However this format does not function:
// desired name of pseudoclass
var oname = 'Obj';
var objs = new Array();
objs.push(new Function('arg', 'this.Arg = arg;'));
// set objs[0] name - DOESN'T WORK
objs[0].prototype.constructor = oname;
// create new instance of objs[0] - works
var inst = new objs[0]('test');
document.write(inst.Arg);
document.write('<BR />Redundant: ');
// check inst name - this one doesn't need to work
try { document.write((inst instanceof objs[0]).toString()); } catch (ex) { document.write('false'); }
document.write('<BR />Required: ');
// check inst name - this is the desired use of instanceof
try { document.write((inst instanceof Obj).toString()); } catch (ex) { document.write('false'); }
Output:
test
Redundant: true
Required: false
Link to JSFiddle.
You've got a couple of things going on here that are a little bit off-kilter in terms of JS fluency (that's okay, my C# is pretty hackneyed as soon as I leave the base language features of 4.0).
First, might I suggest avoiding document.write at all costs?
There are technical reasons for it, and browsers try hard to circumvent them these days, but it's still about as bad an idea as to put alert() everywhere (including iterations).
And we all know how annoying Windows system-message pop-ups can be.
If you're in Chrome, hit CTRL+Shift+J and you'll get a handy console, which you can console.log() results into (even objects/arrays/functions), which will return traversable nodes for data-set/DOM objects and strings for other types (like functions).
One of the best features of JS these days is the fact that your IDE is sitting in your browser.
Writing from scratch and saving .js files isn't particularly simple from the console, but testing/debugging couldn't be any easier.
Now, onto the real issues.
Look at what you're doing with example #1.
The rewriting of .prototype.constructor should be wholly unnecessary, unless there are some edge-case browsers/engines out there.
Inside of any function used as a constructor (ie: called with new), the function is basically creating a new object {}, assigning it to this, setting this.__proto__ = arguments.callee.prototype, and setting this.__proto__.constructor = arguments.callee, where arguments.callee === function.
var Working = function () {};
var working = new Working();
console.log(working instanceof Working); // [log:] true
Working isn't a string: you've make it a function.
Actually, in JS, it's also a property of window (in the browser, that is).
window.Working === Working; // true
window["Working"] === Working; // true
That last one is really the key to solving the dilemma in example #2.
Just before looking at #2, though, a caveat:
If you're doing heavy pseud-subclassing,
var Shape = function () {
this.get_area = function () { };
},
Square = function (w) {
this.w = w;
Shape.call(this);
};
If you want your instanceof to work with both Square and Shape, then you have to start playing with prototypes and/or constructors, depending on what, exactly, you'd like to inherit and how.
var Shape = function () {};
Shape.prototype.getArea = function () { return this.length * this.width; };
var Square = function (l) { this.length = l; this.width = l; };
Square.prototype = new Shape();
var Circle = function (r) { this.radius = r; };
Circle.prototype = new Shape();
Circle.prototype.getArea = function () { return 2 * Math.PI * this.radius; };
var circle = new Circle(4),
square = new Square(4);
circle instanceof Shape; // true
square instanceof Shape; // true
This is simply because we're setting the prototype object (reused by every single instance) to a brand-new instance of the parent-class. We could even share that single-instance among all child-classes.
var shape = new Shape();
Circle.prototype = shape;
Square.prototype = shape;
...just don't override .getArea, because prototypical-inheritance is like inheriting public-static methods.
shape, of course, has shape.__proto__.constructor === Shape, much as square.__proto__.constructor === Square. Doing an instanceof just recurses up through the __proto__ links, checking to see if the functions match the one given.
And if you're building functions in the fashion listed above (Circle.prototype = new Shape(); Circle.prototype.getArea = function () { /* overriding Shape().getArea() */};, then circle instanceof Circle && circle instanceof Shape will take care of itself.
Mix-in inheritance, or pseudo-constructors (which return objects which aren't this, etc) require constructor mangling, to get those checks to work.
...anyway... On to #2:
Knowing all of the above, this should be pretty quick to fix.
You're creating a string for the desired name of a function, rather than creating a function, itself, and there is no Obj variable defined, so you're getting a "Reference Error": instead, make your "desired-name" a property of an object.
var classes = {},
class_name = "Circle",
constructors = [];
classes[class_name] = function (r) { this.radius = r; };
constructors.push(classes.Circle);
var circle = new constructors[0](8);
circle instanceof classes.Circle;
Now everything is nicely defined, you're not overwriting anything you don't need to overwrite, you can still subclass and override members of the .prototype, and you can still do instanceof in a procedural way (assigning data.name as a property of an object, and setting its value to new Function(data.args, data.constructor), and using that object-property for lookups).
Hope any/all of this helps.

Categories