Where toString fails to work? - javascript

function dTree() {
return {
init : function(data) {
this.data = data;
},
node : function(i){
return '' + i;
}
}
};
dTree.prototype.toString = function() {
var str = '';
for(var i = 0; i < this.data.length; i++)
{
str += this.node(this.data[i]);
};
return str;
}
dTree1 = new dTree();
dTree1.init([1,2,3]);
alert(dTree1+'')
I'm expecting it to output 123
How to do it the right way?

That's not how you make constructors. Constructors don't return anything, they manipulate the this object:
function dTree() {
this.init = function(data) {
this.data = data;
};
this.node = function(i){
return '' + i;
};
}
You could also stick the definition of toString into the constructor as well, unless you're doing something special with it:
function dTree() {
this.init = function(data) {
this.data = data;
};
this.node = function(i) {
return '' + i;
};
this.toString = function() {
var str = '';
for(var i = 0; i < this.data.length; i++)
{
str += this.node(this.data[i]);
};
return str;
};
}

You are returning a plain new object from your constructor, the this object inside your constructor is not used at all, and that object is the one that has the right prototype object assigned.
function dTree() {
this.init = function(data) {
this.data = data;
};
this.node = function(i){
return '' + i;
};
}
dTree.prototype.toString = function() {
var str = '';
for(var i = 0; i < this.data.length; i++) {
str += this.node(this.data[i]);
};
return str;
};
dTree1 = new dTree();
dTree1.init([1,2,3]);
alert(dTree1 + '');

Related

TypeError in Javascript

function url_info()
{
var url_val=document.getElementsByClassName("spc-tab");
var current_s=0;
for(var i=0;i<url_val.length;i++)
{
var url_class=url_val[i].className.split(" ");
if(url_class[1]!=null)
{
if(url_class[1]=="selected")
{
current_s=i;
break;
}
}
}
var temp_1=url_val[current_s].text; //**Error here**
return(temp_1);
}
In this function url_info i am getting the TypeError But i don't know why?? .... as My var current_s is defined within the scope and integer...
why write this much of code when one line can do:
function url_info() {
var temp_1 = "";
var url_val = document.querySelector(".spc-tab.selected");
temp_1 = url_val[0].text > 0 ? url_val[0].text : temp_1;
return (temp_1);
}
and second, you don't require to convert your class name to string then split. You just can access them through classlist. Then use contains.
function url_info() {
var url_val = document.getElementsByClassName("spc-tab");
var current_s = 0;
for (var i = 0; i < url_val.length; i++) {
var isSelected = url_val[i].classList.contains("selected");
if (isSelected) {
current_s = i;
break;
}
}
var temp_1 = url_val[current_s].text;
return (temp_1);
}

How to find id in array object then edit and delete a object in oop javascript?

I coding demo student management . But have problem below, please help me resolve them.
The requirement
Manage student : add, edit, remove
Using console building data table. The table contain fiedls: id Name Age Point
Using console call function
List all student have point > = 5;
This is my code:
//
function Student(id, name, age, point) {
this.id = id;
this.name = name;
this.age = age;
this.point = point;
}
Student.prototype = {
setId: function (value) {
this.id = value;
},
getId: function () {
return this.id;
},
setName: function (value) {
this.name = value;
},
getName: function () {
return this.name;
},
setAge: function (value) {
this.age = value;
},
getAge: function () {
return this.age;
},
setPoint: function (value) {
this.point = value;
},
getPoint: function () {
return this.point;
},
};
function StudentController(student) {
this.listStudent = [];
this.id = 1;
}
StudentController.prototype = {
addNew: function (name, age, point) {
var student = new Student(this.id, name, age, point);
this.listStudent.push(student);
this.id += 1;
return student;
},
This is function find id . But it always return last id in array object.
findId: function (id) {
var student = null;
for (var i = 0; i < this.listStudent.length; i++) {
if (id = this.listStudent[i].getId()) {
student = this.listStudent[i];
}
}
return student;
},
This is function edit student. But it can't getId from function findId();
editStudent: function (student) {
var oldStudent = this.findId(student.getId());
console.log('oldStudent', oldStudent);
for (var x = 0; x < this.listStudent.length; x++) {
if (oldStudent = this.listStudent[x].getId()) {
this.listStudent[x] = student;
}
}
},
This function same too editStudent() function.
deleteStudent: function (student) {
var crrentStudent = this.findId(student.getId());
for (var y = 0; y < this.listStudent.length; y++) {
if (crrentStudent.getId() === this.listStudent[y]) {
this.listStudent.splice(y, 1);
}
}
},
This this function sort point of student > = 5. But look like not working :(
// find point student > = 5
findByPoint: function (point) {
var point = '';
for (var i = 0; i < this.listStudent.length; i++) {
if (this.listStudent[i].getPoint() >= point) {
return point;
}
}
},
showStudent: function () {
console.table(this.listStudent);
},
};
var studentController = new StudentController();
studentController.addNew("Hanh", 20, 8);
studentController.findId(1);
studentController.editStudent();
studentController.deleteStudent();
Please help me resolve and explanation. Thank you so much !!
The problem is pretty straight forward, for a comparison operator you need == in if condition, = is for assignment and adding
Change findId() function
findId: function (id) {
var student = null;
for (var i = 0; i < this.listStudent.length; i++) {
if (id == this.listStudent[i].getId()) { // change here
student = this.listStudent[i];
}
}
return student;
},
and in editStudent function
editStudent: function (student) {
var oldStudent = this.findId(student.getId());
console.log('oldStudent', oldStudent);
for (var x = 0; x < this.listStudent.length; x++) {
if (oldStudent == this.listStudent[x].getId()) { //change here
this.listStudent[x] = student;
}
}
},

how can i return the count from a function

hi iam new to javascript, i am trying to return a count from the function my code is like below
my code
function moredbCount(contentMoreArray2, ArrHeading) {
var sampleArr = [];
for (var a = 0; a < contentMoreArray2.length; a++) {
if (ArrHeading !== 'More') {
var fullHeading = ArrHeading + '-' + contentMoreArray2[a].name;
} else {
fullHeading = contentMoreArray2[a].name;
}
sampleArr.push(fullHeading);
}
var sampleCount = sampleHeadingCount(sampleArr);
return sampleCount.then(function (resultantCount) {
return resultantCount; //Here iam getting some count like 10 and returning it to the function;
});
}
var contentCount;
var totalCount = moredbCount(contentMoreArray2, ArrHeading);
totalCount.then(function (resultantTotalCount) {
return contentCount = resultantTotalCount
});
// Here i want to use contentCount 10, But iam getting undefined
Thanks In advance
return contentCount = resultantTotalCount won't return the count, but rather the response of assignment. In contentCount = resultantTotalCount, you are basically assigning the value of resultantTotalCount to contentCount.
You should use
function moredbCount(contentMoreArray2, ArrHeading) {
var sampleArr = [];
for (var a = 0; a < contentMoreArray2.length; a++) {
if (ArrHeading !== 'More') {
var fullHeading = ArrHeading + '-' + contentMoreArray2[a].name;
} else {
fullHeading = contentMoreArray2[a].name;
}
sampleArr.push(fullHeading);
}
var sampleCount = sampleHeadingCount(sampleArr);
return sampleCount.then(function (resultantCount) {
return resultantCount; //Here iam getting some count like 10 and returning it to the function;
});
}
var contentCount;
var totalCount = moredbCount(contentMoreArray2, ArrHeading);
totalCount.then(function (resultantTotalCount) {
return resultantTotalCount
});

For-Loop using function from a Constructor

I'm going through Codecademy's lesson on building a Blackjack game with Javascript.
I'm having trouble coming up with code to put in the for-loop. I'm supposed to write a "score" method in the Hand constructor. It should loop over all of the cards in the Hand, summing up the result of the "getValue" call to each and return that sum.
Can someone help me out please? Thank You.
Here's my attempt, the relevant code is inside the for-loop at the bottom:
// Card Constructor
function Card(s, n) {
var suit = s;
var number = n;
this.getSuit = function() {
return suit;
};
this.getNumber = function() {
return number;
};
this.getValue = function() {
if (number >= 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
};
//deal function
var deal = function() {
var randNum = Math.floor(Math.random() * 13) + 1;
var randSuit = Math.floor(Math.random() * 4) + 1;
console.log(randNum, randSuit);
return new Card(randSuit, randNum);
};
function Hand() {
var handArray = [];
handArray[0] = deal();
handArray[1] = deal();
this.getHand = function() {
return handArray;
};
this.score = function() {
var sum;
for (var i = 0; i < handArray; i++) {
sum += handArray[i].getValue;
return sum;
}
};
};
Well something like this should work :
this.score = function() {
return handArray.reduce( function( memo, val){
return memo + val.getValue();
});
};
I think you need to return the score, outside of the loop, like so:
this.score = function() {
var sum;
for (var i = 0; i < handArray; i++) {
sum += handArray[i].getValue();
}
return sum;
};
This fixed it. Thanks for your help!
this.score = function(){
var sum =0;
for(var i =0; i<handArray.length; i++){
sum += handArray[i].getValue();
};
return sum;
};

How to Write JavaScript Object like that

How to write an Object for using this object like below
var cal = new calculator;
cal.add(10).add(20).miniz(2).div(2);
console.log(cal.result()); // result 14
Here you go, this is one way to do it:
My Example
var calculator = function() {
this.curr = 0;
this.add = function(n) {
this.curr += n;
return this; // returning this at the end of each method is the key to chaining
};
this.miniz = function(n) {
this.curr -= n;
return this;
};
this.div = function(n) {
this.curr = this.curr / n;
return this;
};
this.result = function() {
return this.curr;
};
};
You need to change the instantiation to this:
var cal = new calculator();
Just to get you started:
function Calculator() {
var value = 0;
this.add = function (v) {
value += v;
return this;
};
this.result = function () {
return value;
};
}
var cal = new Calculator;
console.log(cal.add(10).result()); // result 10
may be this is will help some what..
var Calc = function(){
this.value = 0;
};
Calc.prototype.add = function(val){
this.value += val;
return this;
};
then you can use like new Calc().add(100).add(100)
but before make sure understood how prototyping is working,
for ref : a sample
function calculator(){
this.val = 0;
this.add = function(num){
this.val += num;
return this;
};
this.miniz = function(num){
this.val -= num;
return this;
};
this.div = function(num){
this.val /= num;
return this;
};
this.result = function(){
return this.val;
};
}

Categories

Resources