<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
function myarray()
var points = [];
for (var i = 0; i < 10000; i++) {
points.push[Math.round(Math.random() * 10)];
document.write(myarray(points));
}
</script>
<<button onclick="myarray"> OK </button>>
</body>
</html>
I am a beginner with javascript. I want to create a page that displays random numbers from 0 - 10. I am struggling to print an array. Is there a simple solution to this?
You should call the function from outside the function, not in the loop.
The function can just return the array, you can print it in the caller.
points.push is a function, you call it with (), not [].
You're missing {} around the function body.
The function doesn't take any arguments.
function myarray() {
var points = [];
for (var i = 0; i < 100; i++) {
points.push(Math.round(Math.random() * 10));
}
return points;
}
console.log(myarray());
There are too many syntax errors in your code and thsi suggests that you need a proper tutorial than an answer. However, the following snippet shows the conventional way of doing what you want.
function myarray(){
var points = [];
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * 10));
}
document.getElementById('mySpan').innerHTML = 'Randoms: ' + points.toString();
}
myarray()
<span id="mySpan"></span>
You have some syntax errors as well as logic errors.
As pointed out in comments, for loop isn't executed.
A function is defined like function myarray() {}
A function is called with () like this myarray()
Array.push() is a method that you invoke using ().
You also seem to have rogue < in the HTML.
You can use an HTML element (In this case a <output> to display the contents of Array. The join('') method converts array content to a string.
function myarray() {
const el = document.querySelector('output');
var points = [];
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * 10));
}
el.innerText = points.join('');
}
<button onclick="myarray()"> OK </button>
Results: <output></output>
You need to call the function to get the result intended.
points is an array and push is a function so it can be called using ().
function myarray() {
var points = [];
for (var i = 0; i < 10000; i++) {
const randomNumber = Math.round(Math.random() * 10);
points.push(randomNumber);
}
document.write(points);
}
<button onclick="myarray()"> OK </button>
You also need to make an another element or tag so we can place and show the result of our random numbers.
And render the result using something like this:
document.getElementById('generate-number').innerHTML = random_array.
Next, if you render the array directly to an element, it will output with a delimiter, which is a comma ,. The sample output would look like: 2,6,2,1,6. So if you don't want any delimiter, you can remove it by using the .join() function: random_array.join('').
Here's a working example to try:
function generateArray() {
// Creates 10 random numbers in an array
const rand_num_arr = new Array(10).fill(null).map(e => Math.floor(Math.random() * 10));
// Converts array into a string using .join()
const rand_num = rand_num_arr.join('');
// Display the random number in your div element "#generate-number"
document.getElementById('generate-number').innerHTML = rand_num;
}
<div id="generate-number"></div>
<button onclick="generateArray()">Generate Random Numbers</button>
//Arrow Function Expression
const demo = () => {
var temp = [];
for (var i = 0; i < 100; i++) {
temp.push(Math.round(Math.random() * 10));
}
return temp;
}
console.log(demo());
//Normal Function Expression
function demo() {
var temp = [];
for (var i = 0; i < 100; i++) {
temp.push(Math.round(Math.random() * 10));
}
return temp;
}
console.log(demo());
I found few mistakes both in javascript and HTML side + 1 never to do mistake
Some points are already mentioned in the accepted answer but here are a few new ones.
JavaScript Part
In your function myarray you have not used curly braces {}. All the codes of a function lie inside it.
The push is an array method so use a small bracket () not square bracket with it.
You are calling myarray function inside myarray function which causes infinite recursion.
(A never to do mistake) - You wanted to print array on webpage, never use document.write method, because when document.write is executed after a webpage is loaded it overwrites everything on the page. Instead you can use console.log or select an element and inject data in it using innerHTML method. (shown in the code below)
To print an array in javascript you can use index value with the array name. You can parallel print array elements as it is being pushed it reduce execution time. See in the code.
<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<<button onclick="myarray()"> OK </button>>
<p id="output"></p>
<script>
const output = document.getElementById("output");
function myarray() {
var points = [];
for (var i = 0; i < 10000; i++) {
points.push(Math.round(Math.random() * 10));
output.innerHTML += points[i]; // printing array
}
}
</script>
</body>
</html>
HTML Part
One can't say these mistake but rather some modifications (also there is a mistake in the button).
(mistake) When you added onclick event listener to the button then call the function there, by adding parenthesis otherwise function will not execute on button click. Ex: onclick="myarray" => onclick="myarray()"
You should not use angle brackets directly in HTML, it confuses the browser whether it is part of a tag or not. Instead use HTML entity. For < use < and for > use >
Also you can put script tag at bottom of body it looks clean.
Related
I am doing an exercise on JS Hero website:
Write a function add that takes a string with a summation task and returns its result as a number. A finite number of natural numbers should be added. The summation task is a string of the form '1+19+...+281'.
Example: add('7+12+100') should return 119.
The code I have written is as follows:
function add (string) {
let partsArray = string.split("+");
let added = parseInt(partsArray[0]);
for (let i=0; i<=partsArray.length; i++) {
added = added + parseInt(partsArray[i]);
}
return added;
}
It returns NaN. Any ideas how to solve this one?
You were going out of bounds on your array. Also you should just initialize the added to 0 as you start looking at the array from index 0. Note I added some console.logs to give you an idea of how you might debug something like this.
function add (string) {
let partsArray = string.split("+");
console.log("parts", partsArray);
let added = 0;
for (let i=0; i<partsArray.length; i++) {
console.log("i",parseInt(partsArray[i]));
added += parseInt(partsArray[i]);
}
return added;
}
If you add the <= back and run the code with the console.logs you will see in console the following. Note with the <= you have 4 indexes rather than the expected 3. This is because the size is 3 but the array is indexed from zero. When you use < you get the expected answer.
You could also use the reduce method:
function add(string) {
return string.split('+').reduce((accumulator, currentValue) => accumulator +
parseInt(currentValue, 10),0)
}
If you still want to start with the first index ..you can do it like below
function add (string) {
let partsArray = string.split("+");
let added = parseInt(partsArray[0]);
for (let i=1; i<partsArray.length; i++) {
added += parseInt(partsArray[i]);
}
return added;
}
function add(input) {
let myinput = input.split("+") //split your value
let sum = 0;
for (let i = 0; i < myinput.length; i++) {
sum = sum + +myinput[i]; //use + for identify the number value
}
return sum;
}
The simplest possible answer is:
function add(str){
return eval(str)
}
I am building Tetris. I have figured out how to build a HTML table out of a two-dimensional array. However, normal Tetris is played in a ten-by-twenty grid. I am having troubles creating the inner arrays. I looked at this question, but all of the answers don't make sense to me, are based around jQuery, or I can't tell the difference. The code doesn't result in an error. It outputs an empty array, when it should output a length-three array. (This is to test the code.) Can someone tell me what I'm doing wrong?
function array(x, text) {
var toBuild = [];
for (var i; i < x-1; i++) {toBuild.push(text); }
console.log(toBuild);
return toBuild;
}
console.log(array(3, "hello"));
The reason is you are not initializing the i in your for loop. You should assign it to 0.
If you want your code to output an array o length 10 then you should pass 10 to your function and there is not to use x-1. You should use x
function array(x, text) {
var toBuild = [];
for (var i = 0; i < x; i++) {toBuild.push(text); }
console.log(toBuild);
return toBuild;
}
console.log(array(10, "hello"));
The more fancy way of doing the same this is to use fill
const array = (x, text) => Array(x).fill(text)
console.log(array(10, "hello"));
I'm trying to write a Javascript function that counts the vowels in a string by calling another function inside that function, but when I test it in the console it returns 0.
Here is my first function that works fine and recognizes if a string is a vowel:
function isVowel(ch){
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
};
For the second function none of my ideas have worked. Here are a few examples of what I have tried so far:
This one returns me a 0:
function countVowels(str){
var count = 0;
for(var i; i <= str.length; ++i){
if(isVowel(i)){
++count;
}
}
return count;
};
I also tried the above, but removing the .length after str in the for() area.
Another example, but this one gives me an error:
function countVowels(str){
var count = 0
var pattern = /[aeiouAEIOU]/
for(var i = 1; i <= str.length(pattern); ++i){
if(isVowel(i)){
++count;
}
}
return count;
};
I've tried various other functions as well, but for the sake of keeping this post relatively short I won't continue to post them. I'm quite new to Javascript and I'm not sure what I'm doing wrong. Any help would be greatly appreciated!
Try using .match() with the g attribute on your String.
g: global
i: case insensitive
Regexp documentation
function countVowels(ch){
return ch.match(/[aeiouy]/gi).length;
}
var str = "My string";
alert(countVowels(str)); // 2
Although Robiseb answer is the way to go, I want to let you know why you code is not working (I'm referring your first attempt). Basically you made two mistakes in the loop:
As CBroe stated, you are passing i to your isVowel function. i is a integer representing the index of the loop, not the actual character inside the string. To get the character you can do str.substr(i, 1), what means "give me one character from the position i inside the string".
You are not giving a initial value to the i variable. When you create a variable, it is undefined, so you can not increment it.
alert(countVowels("hello"));
function countVowels(str) {
var count = 0;
for (var i = 0; i <= str.length; ++i) {
if (isVowel(str.substr(i, 1))) {
count++;
}
}
return count;
};
function isVowel(ch) {
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
};
UPDATE: You will see that other answers use other methods to select the character inside the string from the index. You actually have a bunch of different options. Just for reference:
str.slice(i,i+1);
str.substring(i,i+1);
str.substr(i,1));
str.charAt(i);
str[i];
i is the index, not the character. It should be:
if (isVowel(str[i])) {
count++;
}
Also, str.length(pattern) is wrong. length is a property, not a function, so it should just be str.length.
You forgot to assign the value 0 to i variable
And parameter for isVowel is the character, not the index of string
Here information about the JS language: https://stackoverflow.com/tags/javascript/info
function isVowel(ch){
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
}
function countVowels(str){
var count = 0;
// you forgot to assign the value to i variable
for(var i = 0; i < str.length; i++){
// isVowel(str[i]), not isVowel(i)
if(isVowel(str[i])){
count++;
}
}
return count;
}
console.log(countVowels('forgot'))
Obviously you should do it this way:
function isVowel(c){
var lc = c.toLowerCase();
if(lc === 'y'){
return (Math.floor(Math.random() * 2) == 0);
}
return ['a','e','i','o','u'].indexOf(lc) > -1;
}
function countVowels(s){
var i = 0;
s.split('').each(function(c){
if(isVowel(c)){
i++;
}
});
return i;
}
console.log(countVowels("the quick brown fox jumps over the lazy dog"));
Which, although less efficient and less useful than other answers, at least has the entertaining property of returning a different count 50% of the time, because sometimes Y.
Here is my code:
board = [];
var rowsNum = 5;
var colsNum = 5;
function printBoard(board) {
for (row in board) {
document.write(" ").join(row);
}
}
function clearAndRestartBoard() {
board = [];
for (i = 0; i < rowsNum; i++) {
board.push("[ ]" * colsNum);
}
}
printBoard(board);
It does not throw an error, but it does not show up in my webpage. Do you know what I am doing wrong?
Just in case, here is the html without the css:
<!DOCTYPE html>
<html>
<head>
<link href="test.css" type="text/css"rel="stylesheet" />
<title> Test! </title>
</head>
<body>
<p id = "script"> <script src = "test.js"> </script> </p>
</body>
</html>
I am very new to JS so thank you so much for any help!
There are several issues there, but the main one is that you never call clearAndRestartBoard, and so board is empty, and so you never output anything.
Here's a list of all of the issues that I see off-the-cuff:
You never call clearAndRestartBoard.
Your code is falling prey to The Horror of Implicit Globals: Declare your variables.
You're using for-in to loop through an array. That's usually not a good idea, though there can be use cases for it; this answer outlines your various options for looping through an array.
"[ ]" * colsNum is NaN because * will convert both of its operands to numbers and then do mathematical multiplication. The string "[ ]" converts to NaN because it cannot be interpreted as a number, and then anything multiplied by NaN is NaN. It isn't colsNum blank arrays. To do that, you'd have to have a second loop creating the row arrays, pushing "[ ]" into them, and pushing those row arrays onto board.
You're using document.write. While that will work for simple experiments, it's not something you want to use in general.
You're calling join on the result of document.write, which I'm fairly certain isn't an array.
I would also suggest that you either use a global board, or always pass it as an argument, but not mix-and-match where one function uses the global and the other uses an argument.
You never output a line break between rows.
Here's a minimal update addressing those:
var board;
var rowsNum = 5;
var colsNum = 5;
function printBoard(board) {
board.forEach(function(row) {
document.write(row.join(""));
document.write("<br>");
});
}
function clearAndRestartBoard() {
var row;
board = [];
for (var r = 0; r < rowsNum; r++) {
row = [];
for (var c = 0; c < colsNum; c++) {
row.push("[ ]"); // If you really wanted the string [ ]
}
board.push(row);
}
}
clearAndRestartBoard();
printBoard(board);
On my website I have a button that selects a random quote from a list of quotes and projects the randomly selected quote into a text box. This is done using JavaScript.
Although I have this working, I'd like an additional piece of code that will prevent the directly subsequent quote being the same as the previous. I'd like any quote used to be able appear again however, just not directly following.
If possible I'd also like it so any quote used does not appear again for a minimum of another 3 clicks - but this would just be a bonus.
Anyway the code I currently have is as follows:
<head>
<script language="javascript"><!--
function GenerateQuote(){var aquote=new Array;
aquote[0]="\"Quote0\"";
aquote[1]="\"Quote1\"";
aquote[2]="\"Quote2\""
aquote[3]="\"Quote3\"";
aquote[4]="\"Quote4\"";
aquote[5]="\"Quote5\"";
aquote[6]="\"Quote6\"";
rdmQuote=Math.floor(Math.random()*aquote.length);
document.getElementById("quoteBox").value=aquote[rdmQuote];
}
-->
</script>
</head>
<body>
<textarea id="quoteBox" readonly></textarea>
<button onClick="GenerateQuote()">Entertainment & Hobbies</button>
</body>
Thanks in advance; I'm sure it won't be too hard for you brainiacs!
Fill an array of quotation, then create a copy.
Scramble the copy of the array (you can just use .sort() method or even better you can look for a js implementation of Fisher-Yates alghoritm
Call pop() over the array on each click event so you will generate every time a different quote until the array is fully consumed
When length of the array is zero goto 1)
Reference:
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop
<head>
<script type="text/javascript">
!function (){
var quotes = ["quote0", "quote1", "quote2", "quote3", "quote4", "quote5", "quote6", "quote7", "quote8"],
shuffleAfter = quotes.length, cur = 0;
function shuffle( arr ) {
var l = arr.length, j, i, tmp;
for( i = l - 1; i > 0; --i ) {
j = ( Math.random() * ( i + 1 ) ) >>> 0;
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
}
function generateQuote(){
var r;
if( cur++ % shuffleAfter === 0 ) {
shuffle(quotes);
}
r = quotes.shift();
quotes.push( r );
return r;
}
window.generateQuote = generateQuote;
}()
</script>
</head>
<body>
<textarea id="quoteBox" readonly></textarea>
<button onClick="document.getElementById('quoteBox').value = generateQuote()">Entertainment & Hobbies</button>
</body>
Results from calling generateQuote() 27 times:
2,9,7,5,8,1,3,4,6,9,6,1,7,5,4,3,2,8,3,1,6,5,2,7,9,4,8,2
As you can see, after a full cycle the quotes are shuffled again and there is a chance the same quote will appear if it was last in the last cycle and is first in the new cycle. It should be much better than playlist shuffling in my mp3 player at least :P
use
var lastQuote=-1;
outside your function, then
var rdmQuote=lastQuote;
while (rdmQuote==lastQUote) rdmQuote=Math.floor(Math.random()*aquote.length);
lastQuote=rdmQuote;
inside your function
you can tweak dontRepeatUntil to sweats your need
There's certainly better way but this one should work
var latestQuote = []
, dontRepeatUntil=3
, rdmQuote = null
, quotes=[
"\"Quote0\""
,"\"Quote2\""
,"\"Quote3\""
,"\"Quote4\""
,"\"Quote5\""
,"\"Quote6\""
]
;
function GenerateQuote(){
if(latestQuote.length >= dontRepeatUntil){
latestQuote = latestQuote.slice(latestQuote.length-dontRepeatUntil+1);
}
do{
rdmQuote=Math.floor(Math.random()*quotes.length);
}while(latestQuote.join(',').match(new RegExp('(^|,)'+rdmQuote+'(,|$)')));
latestQuote.push(rdmQuote);
document.getElementById("quoteBox").value=quotes[rdmQuote];
}