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();
Related
I need to make a grid that looks like this in javascript using one function:
x---------
xx--------
xxx-------
xxxx------
xxxxx-----
xxxxxx----
xxxxxxx---
xxxxxxxx--
xxxxxxxxx-
xxxxxxxxxx
and this:
x---------
xx--------
xxx-------
xxxx------
xxxxx-----
xxxxx-----
xxxx------
xxx-------
xx--------
x---------
//Build Matrix
function initMatrix(max) {
var myMatrix = [];
var i;
for(i = 0; i < row; i++){
myMatrix.push([]);
var j;
for(j = 0; j < col; j++) {
if(j < max) {
myMatrix[myMatrix.length - 1].push('*');
} else {
myMatrix[myMatrix.length - 1].push('-');
}
}
}
return myMatrix;
}
More of this code can be viewed here
https://jsfiddle.net/0yc7acev/
Thanks in advanced for the help!
Hi I've made you this document that explains how to do this and has both solutions: https://tonicdev.com/tonic/stars-example . Let me know if you have any questions!
Edit: I realized after the fact that you wanted them in a matrix, not a string, so I've made a slight modification to put them in a matrix for you: https://tonicdev.com/tonic/stars-matrix (the old one still shows how to put them all in string).
The solution at the end is just:
function drawStars(starCounts)
{
return starCounts.map(function (starCount)
{
return (new Array(starCount + 1).join("*") +
new Array(lineLength - starCount + 1).join("-")).split("")
});
}
where starCounts is an array.
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
Below js function is working well in html page. But when i put it into selenium.getEval in RC to wonder to get return value j. It cannot work, also without any error. Do i miss some function call format? Thanks in advance!!!
function GetTableRow()
{
var table;
var ctext = "bb";
var cname = "mps_tableborder";
var col = 0;
var j;
for (i = 0; i < document.getElementsByTagName("table").length; i++) {
if (cname==document.getElementsByTagName("table")[i].className) {
table = document.getElementsByTagName("table")[i];
break;
}
}
for (j = 0; j < table.rows.length; j++){
if (ctext == table.rows[j].cells[col].innerText){
break;
}
}
return (j);
}
You can provide only the contents of method. Not the entire method. Try by removing the method starting [ function GetTableRow() { ] and method ending [ } ] and give it to getEval method and see what it returns! Ideally it should work fine.
I have a problem with this script, something is going wrong.
Rnumer stays undefined.This script should return and write all uneven digits from the random number list. Can someone tell me what I do wrong. Thanks in advance
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
// document.write(Rnumber[i] + "<br/>");
}
function unevenAndDivisible(Rnumber)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder = parseInt(Rnumber[i])%2;
}
return remainder;
}
document.write(unevenAndDivisible());
Changed to
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
// document.write(Rnumber[i] + "<br/>");
}
function unevenAndDivisible(Rnumber)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder[i] = Rnumber[i]%2;
}
return remainder;
}
document.write(unevenAndDivisible(Rnumber));
but now i get the result :
0,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,1....
I simply want maybe I asked it wrong the first time, to write al uneven numbers from the random list of Rnumbers
Then I need to divide that through 7 and return that.
EDIT
Allmost all problems are clear , thanks everyone for that.
Their is still one question left:
In this code below it only take the first uneven value from remainder and I want that it takes all values that are uneven to the next if statement to check %7.
Maybe you see the problem better if you run it for youreself
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
}
function unevenAndDivisible()
{
var remainder = [];
var answer = [];
for (i = 0; i<= 100; i++)
{
if (Rnumber[i]%2 !== 0)
{
remainder.push(Rnumber[i]);
for (c = 0; c <= remainder.length;c++)
{
if (remainder[c]%7 == 0)
{
answer.push(remainder[c]);
}
}
}
}
return answer;
}
answer = unevenAndDivisible();
document.write(answer);
Problem solved , Thanks everyone
You don't need to pass Rnumber to the function, as it's already available in scope:
function unevenAndDivisible()
{
var remainder = [];
for (i = 0; i<= 100; i++)
{
if (Rnumber[i]%2 !== 0) {
remainder.push(Rnumber[i]);
}
}
return remainder;
}
remainder = unevenAndDivisible();
console.log(remainder);
JS Fiddle demo.
Edited in response to question from OP (in comments to question, above):
...can someone explain what this mean: var remainder = [];
Sure, it's array-literal notation, which is equal to: var remainder = new Array();, it's just a little more concise, and I prefer to save myself the typing. I get the impression, from JS Lint, whenever I use var x = new Array(); therein that the above version is generally preferred (since it complains otherwise), but I don't know why.
Either pass Rnumber to the function unevenAndDivisible or omit it from the argument list. Since it is an argument, it has more local scope than the initial declaration of Rnumber.
Your problem is the line
function unevenAndDivisible(Rnumber)
You are passing in Rnumber in as an argument, but when you call unevenAndDivisible()
you are not passing it it.
Consequently for the body of the function Rnumber is undefined (cause you passed nothing in)
The following snippet is equivalent to what you wrote nad might explain better
function unevenAndDivisible(xyz)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder = parseInt(xyz[i])%2;
}
return remainder;
}
then called as
unevenAndDivisible(undefined)
to fix it remove the argument from the call definition
i.e. define it as
function unevenAndDivisible()
1 - you is not defining the Rnumber value that's function argument.
2 - in loop, you're defining remainder to divised value of ranumber and is not saving in array; try:
change:
remainder = parseInt(Rnumber[i])%2;
to
remainder[i] = parseInt(Rnumber[i])%2;
var array = [],
i = 100;
while (i--) {
var random = Math.random()*i|0;
if(random % 2)
array.unshift(random);
}
alert(array);
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>