Intellisense pretty much stops working as soon as I call function "meanValue"
I think I narrowed it down but I can't quite figure it out. Apparently there is something wrong with the function "meanValue" because after I call it within another function, all forms of intellisense stop working...Here is my code. Intellisense doesnt work for everything inside function test after I call the meanValue function...
I have no clue the meanValue function seems fine to me??
//
EDIT: I've narrowed it down. Apparently any function where I have If(arr[0].length) type of syntax, it pretty much fails. One thing to note that is the functions run fine and debug fine but for some reason intellisense doesnt like this.
Anyone know what another way to check if something is defined or not? I want to check to see what kind of array I am looking at, if its a multidimensional array or not.
Thanks!!!
//
<script language="javascript" type="text/javascript">
function meanValue(arr) {
var mean;
var sum = 0;
if (arr[0].length) {
for (var j = 0; j < arr[0].length; j++) {
sum += arr[0][j];
}
mean = (sum) / arr[0].length;
}
else {
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
mean = (sum) / arr.length;
}
return mean;
}
function test(a, b) {
var testing = 5;
var oranges = meanValue(a);
}
var a = [1, 3, 4];
var b = [4, 5, 6];
</script>
In test() you have a variable testing, that has nothing assigned to it after =. That could be one of the problems.
Who is calling test()?
I was able to reproduce the issue in my Netbeans.
The problem seems to stem from a mixing of two languages in one file for certain IDEs. (Is this a .php file with some Javascript in it?)
For some reason, the IDE intellisense engine is trying to parse the less-than (<) symbol in that chunk of code as if it were trying to validate XML, which Javascript isn't. So, of course, it's failing.
Try wrapping that code in [CDATA -- it should resolve the issue.
So the example above, modified, would be:
<script language="javascript" type="text/javascript">
//<![CDATA[
function meanValue(arr) {
var mean;
var sum = 0;
if (arr[0].length) {
for (var j = 0 ; j < arr[0].length ; j++)
{
sum += arr[0][j];
}
mean = (sum) / arr[0].length;
}
else
{
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
mean = (sum) / arr.length;
}
return mean;
}
function test(a, b) {
var testing = 5;
var oranges = meanValue(a);
}
var a = [1, 3, 4];
var b = [4, 5, 6];
//]]>
</script>
Related
Getting a NaN error in this addition function for script code, although there is no type conversion from string to int: Any suggestions?
var add = function(a, b) {
var i = 0,
sum = 0;
for (i = 0; i <= arguments.length; i++) {
sum += arguments[i];
}
return sum;
};
console.log(add(10, 20, 30, 40, 50));
For loop condition part should be i < arguments.length
arguments.length[arguments.length] will be undefined
In the last iteration of the for loop, code was trying to add 150 + undefined which resulted in NaN
Best way to figure out these type of problems is by debugging
Following are some debugging method
Use console statements and check what is happening
Use a debuggers and check line by line what is happening in your code
I personally use node debugger.
You check line by line what is happening in your code and check values
of variable on the fly
Following is working code
var add = function (a,b) {
var i = 0,
sum = 0;
for (i = 0 ; i < arguments.length ; i ++) {
sum += arguments[i];
}
return sum;
};
console.log(add(10,20,30,40,50));
You are setting the for loop's condition field incorrectly.
It should be:
(i = 0; i < arguments.length; i++)
(Notice the use of < instead of <=)
The problem is that you tried to add arguments[5] (because the length is 5, but arrays start at 0) which is undefined.
Number + undefined = NaN
Working my way through 'Eloquent Javascript' and I'm hitting a bit of a roadblock in understanding how to properly use if with for statements in the language. I'm supposed to write a function that counts all instances of the uppercase 'B' in a given string. The code I've written thus far:
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {}
counter += 1;
}
}
console.log(countBs("BBC"));
expected output: 2
actual output: undefined
Is my loop going wrong, or my 'if'?
You have two bugs
You are incrementing your counter outside of the if statement.
You have no return statement.
The following can be used:
function countBs(s){
var counter = 0;
for(i = 0; i < s.length; i++){
if ('B' == s.charAt(i)) {
counter += 1; // this needs to be inside the if statement
}
}
return counter;
}
Your function does not have a return statement.
A few issues.
function countBs(s) {
var counter = 0;
for (i = 0; i < s.length; i++) {
if ('B' == s.charAt(i)) {
++counter;
}
}
return counter;
}
document.write(countBs("BBC"));
You were not returning counter at the end of the function
Your if statement was opened, then immediately closed, so nothing happens if the character was B
Even if you returned counter and fixed the above 2 errors, the function still would have exited after 1 B was found. To fix this, move the return after the for ends.
If you're interested, the same problem can be solved with this one-liner:
function countBs(s) {
return s.match(/B/g).length;
}
document.write(countBs("BBC"));
Which finds all B characters (case-sensitive), puts them into an array, then returns how many items are in that array.
So I`m working ona simple JS code. We just started to learn about functions.
I need to make a function named "printStars".
I need to take a number from the user and accourding that number print "*".
This is what I did:
<script>
function printStars()
{
var n = Number(prompt("Insert number of stars:","0.."));
for (i = 0; i < n; i++)
{
document.write("*");
}
}
var stars = printStars();
document.write(stars);
</script>
In the end I get my result with a minus of getting "undefined".
I would love to get some help, and an explanation why is keep happening.
Thanks guys!
jsfiddle demo
function printStars(){
var n = prompt("Insert number of stars:","0..");
var stars='';
for (i = 0; i < n; i++){
stars+='*';
}
$('body').html(stars) //jsfiddle does not allow document.write()
//document.write(stars);
}
//call the function
printStars();
You don't need this
document.write(stars);
You just need this:
// This will make you function to be evaluated and
// the code in your function will be executed.
printStars();
function printStars()
{
var n = Number(prompt("Insert number of stars:","0.."));
for (i = 0; i < n; i++)
{
document.write("*");
}
}
printStars();
I am trying to build a simple script to work with a Google Spreadsheet that looks like this:
It shows me which of my clients use which modules of each layer. Each client may use how many modules he wants to.
What I need to do is count how many clients have all the modules installed (or the three layers, it's the same).
I've tried to do this using the built-in functions but have not succeed.
Now I'm trying to do my own function, that looks like this:
function countTotalModByClient(values) {
var quantMod=0;
var quantClient=0;
for (var i=0; i<values.length; i++) {
for(var j=0; j<values.length; j++) {
if(values[i][j]=="X") {
quantMod++;
}
}
if(quantMod==15) { // total number of modules
quantClient++;
}
quantMod=0;
}
return quantClient;
}
But it always return the same result: 0.
At my sheet, I'm calling the function like this: =countTotalModByClient(B3:P6)
P.S.: Sorry about the magic number in the code, I´ll fix this. =)
This should be possible with a standard formula (although maybe a little complex).
=countif(ArrayFormula(MMULT(--(B3:P6="X"), transpose(column(B3:P2)^0))), 15)
should return the number of clients with a count of 15 in their row..
Can you check if that works ?
Or if you prefer a custom function, give this a try:
function countTotalModByClient(values) {
var quantClient = 0;
for (var i = 0; i < values.length; i++) {
if (values[i].countItem("X") === 15) quantClient += 1;
}
return quantClient;
}
Array.prototype.countItem = function (item) {
var counts = {};
for (var i = 0; i < this.length; i++) {
var num = this[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
return counts[item] || 0;
}
Example spreadsheet
function averageCalculator (numvalues) {
for(i=0, i <= numvalues, i++>) {
var score = prompt("input the score")
result1 += score;
}
alert(result1 / 3);
}
this function is later triggered by a button with onclick="averageCalculator (2)
<input type="button" value="Click for the average" onclick="averageCalculator (2)">
any ideas why its not working? it should prompt you for 2 values and then alert you with the average. not sure whats wrong.
Your code has multiple issues. The for loop is not well formatted and you need to terminate statements with a semi-colon. Also you need to declare variables. And your loop will run numvalues+1 times which is why i removed the = in your loop. Also if you want to calculate an average you want to divide by numvalues.
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += score;
}
alert(result1 / numvalues);
}
On top of the invalid syntax you will run into a common "problem" with javascript here. The inputs are treated as strings and instead of being added they will be concatenated. Providing 2 and 2 as scores will result in 11. 2 concatenated with 2 = 22 / 2 = 11. You need to cast the value to a number explicitly before adding them together:
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += Number(score);
}
alert(result1 / numvalues);
}
Above code will correctly return 2
The syntax of your for-loop is wrong:
for(i=0, i <= numvalues, i++>) {
should be
for(i=0; i <= numvalues; i++) {
Tip: Also, it's better to use
for(var i=0; i <= numvalues; i++) {
since then i will be a local variable instead of a global one.
Try like this
for(var i=0; i <= numvalues; i++){}
An alternative solution (using a functional programming libary, like Underscore.js):
function averageCalculator(numValues) {
var numbers = _.map(_.range(numValues), function(element) {
return +prompt('input the score');
});
var result = _.reduce(numbers, function(memo, number) {
return memo + number;
}, memo);
alert(result / 3);
}
While a little bit more complicated (and less efficient), you'll get rid of loops altogether.
EDIT
The +prompt('input the score') does effectivly the same as Number(prompt('input the score')).