Can´t call the function in JavaScript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am making a calculator, where you write in a text input. For testing the code, I just made up a random count and a few "ifs". Here´s the code:
var res=0, operator, pattern, num1, num2
myText= "2~3+2"
pattern= /([\+\-\*\~\V/])/;
var nums= myText.split(pattern);
function makeCount() {
num1= Number(num1);
num2= Number(num2);
if (operator=== "~") {
num1= Math.pow(num1,num2);
nums.splice(i-1, 3, num1);
}
if (operator=== "+") {
num1= num1+num2;
nums.splice(i-1, 3, num1);
}
}
function SrtLoop() { //checks all the numbers
for (var i=0; i<nums.length; i++) {
if (nums[i]=== "~") {
num1=nums[i-1];
num2=nums[i+1];
operator="~";
makeCount();
}
if (nums[i]=== "+") {
num1= nums[i-1];
num2= nums[i+1];
operator="+";
makeCount();
}
}
}
SrtLoop();
res=num1;
Before, I just put the the for loop, without a function, but I realized, after the program checked the operators, it would not check again. So I thought that putting the for loop inside a function, I would call it once, and after making the count it would call the for loop function again. Turns out that without the function, in the end, res=10 (expected), with the function, without calling it, res=undefined (expected), but calling the function destroys all the code and nothing appear in the screen.
Note: i am new here and sorry if my English is bad

Your makeCount function has no reference to i whatsoever. You haven't declared i as a global variable (although that's not a great practice). You also haven't passed it as an argument to the makeCount function.
var res=0, operator, pattern, num1, num2
myText= "2~3+2"
pattern= /([\+\-\*\~\V/])/;
var nums= myText.split(pattern);
function makeCount(i) {
num1= Number(num1);
num2= Number(num2);
if (operator=== "~") {
num1= Math.pow(num1,num2);
nums.splice(i-1, 3, num1);
}
if (operator=== "+") {
num1= num1+num2;
nums.splice(i-1, 3, num1);
}
}
function SrtLoop() { //checks all the numbers
for (var i=0; i<nums.length; i++) {
if (nums[i]=== "~") {
num1=nums[i-1];
num2=nums[i+1];
operator="~";
makeCount(i);
}
if (nums[i]=== "+") {
num1= nums[i-1];
num2= nums[i+1];
operator="+";
makeCount(i);
}
}
}
SrtLoop();
res=num1;
See the fiddle: https://jsfiddle.net/0f2yrxgu/
It doesn't log anything as I really don't understand what you're doing here. However, the error is gone.

The variable i is undefined in function makeCount(). Modify as follows:
function makeCount(i) {
//Your code
}
Modify the calls as follows:
makeCount(i);

Related

Variable returns undefined no matter what it is set to [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
In this function, I initialize the variable allowDial() and later define it.
I was having some problems with its value so I added a console.log to the end of the offHook() function. I define it right before. No matter what I set allowDial to, it returns undefined - be it number, boolean, string, etc.
Why is console.log returning undefined? If I can't get console.log to accurately report its value, I don't see how I can make this implementation of the variable work.
Here is the relevant code:
var allowDial;
var availableNumbers = ["0", "911", "1 (847) 765-1008" , "867-5309", "1 (212) 456-1414", "555-1212", "555-5555"];
function numberSuggestion() {
var randomNumber = Math.floor(Math.random() * (availableNumbers.length));
var suggestedNumber = availableNumbers[randomNumber];
document.getElementById("suggestion").innerHTML = "How about dialing <strong id='suggestedTelephoneNumber'>" + suggestedNumber + "</strong>? Don't like this number? Click the button above again!";
}
var dialTone;
function offHook() {
document.getElementById("WE2500").style.display = "none";
document.getElementById("dialPad").style.display = "block";
dialTone = new Audio('dialTone.m4a');
dialTone.play();
allowDial === true;
console.log(allowDial);
}
You are not assigning any value to allowDial. === is used for comparison, not assignment. For assigning a value you should use allowDial = true;
You don't assign any value to allowDial.
allowDial = true;
Example:
var tmp;
testVar(tmp); // "is null"
tmp = null;
testVar(tmp); // "is null""is definitive null"
testVar()
function testVar(variable) {
if(variable == null) {
console.log("is null");
}
if(variable === null) {
console.log("is definitive null");
}
}

How to make this function call add(4)(5)(6) work? which will return 15 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I know one way is there any other way to make this type of function call and get the correct addition.
My answer:
function add(x) {
return function(y) {
return function(z) {
return x + y + z
}
}
}
add(4)(5)(6)
It means that the first function returns another function and then that returned function is called immediately then that function returns another function which is then called immediately which will give us the final answer.
As others have mentioned, you can't quite do that. You could create a fluent interface sort of similar to that though, by extending the Number prototype:
Number.prototype.add = function(num) {
return this.valueOf() + num;
}
Then, you could use it like this:
// Instead of add(2)(7)(11):
(0).add(2)
.add(7)
.add(11);
// Or:
(2).add(7).add(11);
Not sure I'd recommend actually doing that, but it's a fun exercise.
You should pass an array to your function as parameter and make a loop on it:
function add(num) {
var sum = 0;
for (var i = 0; i < num.length; i++) {
sum += num[i];
}
return sum;
}
alert(add([10,20,30]));//will return 60
You can't do that. The first set of parenthesis is there to pass the parameter to your function. You are allowed to pass more than one parameter to your function like this:
var total = add(2, 8);
Inside your add function, you be able to create a sum of every parameter using the arguments keyword:
function add() {
var returnValue = 0;
for (i = 0; i < arguments.length; i++) {
returnValue += arguments[i];
}
return returnValue;
}
The second set of parenthesis will be applied on the value (or object) returned by your function. add(2)(8) would be the same as writing 2(8), which doesn't make sense.

Accessing An Array from within a function using JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I searched the forum but didn't see a similar question or answer for the question I am about to ask, however if it is duplicated please provide a link and I will view the answer in that post.
Is it possible to access objects in a array from within a closure/ function? I am attempting to do so for the purpose of experimentation.
Here is the code I put together in firebug. I am receive 'undefined'.
var checkers = [1, "string", null];
var i, txt = "";
function myFunction(checkers){
for(var i = 0; i < checkers.length; i++ ){
txt += checkers[i] + " ";
console.log(txt)
}
}
myFunction(checkers);
Absolutely possible, one of JavaScript's strenghts.
Your issue is that you aren't calling your function. Also you don't need a parameter to myFunction since it closes over the context and knows about checkers.
Just delete the paramter and after your code add myFunction() to call it.
var checkers = [1, "string", null];
var i, txt = "";
function myFunction(){
for(var i = 0; i < checkers.length; i++ ){
txt += checkers[i] + " ";
console.log(txt)
}
}
myFunction();
The reason you are getting undefined is because theres not value returned to the console when declaring a function, just like you'd get undefined if you ran:
var t = 'asd'
var checkers = [1, "string", null];
var i, txt = "";
function myFunction(checkers){
for(var i = 0; i < checkers.length; i++ ){
txt += checkers[i] + " ";
console.log(txt)
}
}
myFunction(checkers);
I just ran it and I get:
1
1 string
1 string null
undefined
Since the function doesn't return anything, Firebug displays undefined at the end.

Can I refactor this code in any way in javascript? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I have a 'render' function:
render: function(playerId){
this.getTotalPoints(playerId);
// and some other code after this;
}
This 'render' function may be executed with or without a playerId. This is the getTotalPoints function:
getTotalPoints: function(playerId){
if(playerId){
this.allplayers[playerId].totalPoints = this.calculatePoints(this.allplayers[playerId].cards);
}else{
this.allplayers.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
}
And the third function that actually calculates the points
calculatePoints: function(cards){
points = 0;
for( var i = 0; i < cards.length; i++){
points+=cards[i].points;
};
return points;
}
I am repeating myself in getTotalPoints, where I have a call to this.calculatePoints - one for a single player and then one for all the players, depending on whether the playerId is set or not.
Is there any chance I can avoid this and simplify the code?
I would do something like:
getTotalPoints: function(playerId){
var selected = playerId ? [this.allplayers[playerId]] : this.allplayers;
selected.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
However, since you're changing the state of the players, I would not call the function getTotalPoints, maybe computeTotalPoints?
I see two different functions: calculatePointsForPlayer and calculatePointsForPlayers. Second function will call first function.

JavaScript factorial [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Cant wrap my head around arguments.callee and why truefactorial = 120. Some help would be much appreciated
function factorial(num){
if (num <= 1) {
return 1;
} else {
return num * arguments.callee(num-1)
}
}
var trueFactorial = factorial;
factorial = function(){
return 0;
};
alert(trueFactorial(5)); //120
Inside a function, arguments.callee refers to that function.
So factorial is recursive - it calls itself. No matter what name you might use for it.
Redefining the name factorial to reference a different function has no affect on the first definition, because nowhere in that first definition does it use the name factorial.
As noted in the comments arguments.callee is deprecated and you should not use it (it won't even work if your code is running in strict mode). However, if you replace arguments.callee with factorial in your example, the end result will not do anything useful:
function factorial(num){
if (num <= 1) {
return 1;
} else {
return num * factorial(num-1);
}
}
var trueFactorial = factorial;
factorial = function(){
return 0;
};
alert(trueFactorial(5)); // 0
This is because factorial gets reassigned before your function is called, and when it ultimately tries to call factorial() inside the function, the new factorial() just produces a 0.
There is a way around this, and that is to use a named function expression:
var factorial = function factorial (num) { // <--- This line
if (num <= 1) {
return 1;
} else {
return num * factorial(num-1);
}
}
var trueFactorial = factorial;
factorial = function(){
return 0;
};
alert(trueFactorial(5)); // 120 (Yay!)
If you do this, even if the factorial variable is reassigned outside of the function, it will keep its original meaning inside the function, and will not break.

Categories

Resources