What's wrong with this javascript code? (body script calling head function) - javascript

Why does the following not produce any result? I get a blank page. I kept modifying/simplifying the code to see where the problem is and it seems to be with the line
"var count = NbnamePattern(names)"
Things seem to work when the body script calls a function defined in the head but with no arguments passed.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2 Q4</title>
<meta charset="utf-8" />
<script>
function NbnamePattern(var names) {
var count = 0;
for (var i in names) {
if (names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
}
return count;
}
</script>
</head>
<body>
<p></p>
<script type="text/javaScript">
var names = new Array("freddie", "bob", "mieke", "yahoo2", "georgey"); var count = NbnamePattern(names); document.getElementsByTagName("p")[0].innerHTML = "The number of names having these two patterns (/ie$/) and (/y$) in the array is:" + count;
</script>
</body>
</html>

function NbnamePattern(var names){
var count = 0;
for(var i in names)
if(names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
return count;
}
should be
function NbnamePattern(names){
var count = 0;
for(var i in names)
if(names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
return count;
}
The functions in javascript dont take types, it should just be name

you need to remove the var from NbnamePattern(var names) function
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2 Q4</title>
<meta charset="utf-8" />
<script>
function NbnamePattern(names) {
var count = 0;
for (var i in names) {
if (names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
}
return count;
}
</script>
</head>
<body>
<p></p>
<script type="text/javaScript">
var names = new Array("freddie", "bob", "mieke", "yahoo2", "georgey"); var count = NbnamePattern(names); document.getElementsByTagName("p")[0].innerHTML = "The number of names having these two patterns (/ie$/) and (/y$) in the array is:" + count;
</script>
</body>
</html>

Related

function to return something x amount of times,specified by a parameter? [duplicate]

This question already has answers here:
Repeat a string in JavaScript a number of times
(24 answers)
Closed 1 year ago.
I have a function which returns an html element like addSpan(times),is there a way to return this element as many times as specified in the parameter items ?
vanilla js is welcomed!
function addSpan(times){
const span = `<span>This is a span</span>`
return span
}
$("body").append( addSpan(2) ) //is supposed to add 2 spans
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Please use Array.map() function.
function addSpan(times){
const spans = [...Array(times)].map(val => "<span>This is a span</span>").join('')
return spans
}
use yield
function* addSpan(times){
for(var i=0; i < times; i++){
const span = document.createElement('span');
span.innerText = "Some text" ;
yield span;
}
}
for (let element of addSpan(2)) {
$("body").append(element)
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Yes. Possible.
Like this:
function addSpan(count)
{
let result = "";
for (var i = 0; i < count; i++)
{
result += "<span>This is a span</span>";
}
return result;
}
You need loop until you reach the count and return spans.
function addSpan(times){
let spans = "";
const span = `<span>This is a span</span>`;
for (let i = 0; i < times; i++){
spans += span;
}
return spans;
}
$("body").append(addSpan(2));
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>

how to initialize a member of JS array?

I just wrote this in order to take n from user and also n names , and then print them on screen after clicking on button , but i cant initialize my array ...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
var n;
var i =0;
var names = [];
function mf1(){
n=parseInt(document.getElementById("n").value);
}
function mf2(){
if (i<n){
names[i]=document.getElementById("nam").value;
i++;
document.getElementById("rem").innerHTML=names[i];
}
}
</script>
inset n : <input type="text" id="n"> <button onClick="mf1()">take n</button>
insert name: <input type="text" id="nam"> <button onClick="mf2()"> take name</button>
<p id="rem"></p>
</body>
</html>
The problem is that in function mf2 you can't access names[i] because you increment i++ before.
var n;
var i = 0;
var names = [];
var input1 = document.getElementById("n");
var input2 = document.getElementById("nam");
function mf1(){
n = parseInt(input1.value);
console.log(n);
}
function mf2(){
if (i < n){
names[i] = input2.value;
console.log(names);
document.getElementById("rem").textContent = names[i];
i++;
}
}

Random number generation/shuffling issue

Okay so, I'm trying to create an application where when you click a button it Generates and Displays a concatenated sequence of unique Numbers between 1 and 76. I have it generating 1 -78 randomly with no dupes but I am unsure as to how I would make it so when it comes to displaying it, it displays 1 number and then increments +1 with every click.
So first click [28]
second click [28, 33] and so on without duplicates. here is the code I have so far
window.onload = onclick;
function onclick() {
document.getElementById("BtnCall").onmousedown = GenNumber;
}
function GenNumber() {
var num = LoadNumbers(1, 76);
num = shufflearray(num);
for (i = 0; i < 1; i++) {
ShowArray(num);
}
};
function LoadNumbers(min, max) {
var arr = [];
for (var i = min; i <= max; i++) {
arr.push(i);
}
return arr;
}
function shufflearray(input) {
var out = [];
while (input.length > 0) {
var i = Math.random() * input.length;
var a = input.splice(i, 1);
out.push(a);
}
return out;
}
function ShowArray(m) {
for (var i = 0; i < m.length; i++) {
document.getElementById("usednum").innerHTML += (m[i]+', ');
}
}
Thanks for any support/help :)
needs to behave/like this
https://gyazo.com/bebb7c58c402934050be8bc9be29e183
instead of this:
This happens with one single click
I think you're making random number concatenation one after another logic TOO complicated with your existing code like GenNumber(), LoadNumbers() and shufflearray() method. I just post an example answer that will fulfill what you want to do as per "Need to behave like this" (If I were you then I'll try this way).
By the way I've also posted an answer with your existing code also.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Generate Random Number</title>
</head>
<body>
<p id="show_random"></p>
<script type="text/javascript">
var randoms = [];
function makeid() {
var randomnumber = Math.ceil(Math.random() * 76);
randoms.push(randomnumber);
//console.log(randoms);
document.getElementById('show_random').innerHTML = randoms.join(' ');
}
</script>
<input type="button" style="font-size:9pt" value="Gen Random" onclick="makeid()">
</input>
</form>
</body>
</html>
See it with your code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Generate Random Number</title>
</head>
<body>
<p id="usednum"></p>
<script type="text/javascript">
window.onload = onclick;
function onclick() {
document.getElementById("BtnCall").onmousedown = GenNumber;
}
function GenNumber() {
var num = LoadNumbers(1, 76);
num = shufflearray(num);
var single = Math.ceil(Math.random() * num.length);
ShowArray(single); //with you existing code you're passing whole array
};
function LoadNumbers(min, max) {
var arr = [];
for (var i = min; i <= max; i++) {
arr.push(i);
}
return arr;
}
function shufflearray(input) {
var out = [];
while (input.length > 0) {
var i = Math.random() * input.length;
var a = input.splice(i, 1);
out.push(a);
}
return out;
}
function ShowArray(m) {
document.getElementById("usednum").innerHTML += (m + ', ');
}
</script>
<input type="button" style="font-size:9pt" value="Gen Random" id="BtnCall">
</input>
</form>
</body>
</html>

How to compare the current variable with current type?

In my code I try to comapare the current element from the array tmp with the types string and number. With this compare I want to print in the console the result different, i.e. if is a string to print it on the same line(the whole word), the next word to be on the second line and so on. But if is a number every digit to print in the new line.
Output number
Input string
Output string
HTML
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Exercises in JS</title>
<script src="exercises.js"></script>
<body>
<label for="myText">Input array:</label>
<input type="text" id="myText">
Submit
<br/>
<br/>
<label for="myText2">Input for delete:</label>
<input type="text" id="myText2">
Submit
</body>
</head>
</html>
Javascript
window.onload = function(){
inputBox =document.getElementById("myText");
btn = document.getElementById('sub');
inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');
btn.addEventListener("click",function(event){
event.preventDefault();
saveArr(inputBox.value);
});
btn2.addEventListener("click",function(event){
event.preventDefault();
removeItemAndprintNewArray(inputBox.value, inputBox2.value);
});
function saveArr(arr) {
var rv = [];
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
function removeItemAndprintNewArray(rv, number) {
var tmp = [],
st = "";
for(var index in rv){
if(rv[index] !== number){
tmp.push(rv[index]);
}
}
for (var i = 0; i < tmp.length; i++){
if (typeof(tmp[i]) == "String"){
st += tmp[i];
console.log(st);
}
else if (typeof(tmp[i]) === "Number"){
st += tmp[i];
console.log(st[i]);
}
}
}
}
Javascript automatically makes type conversations, and if conversation fails it returns NaN value instead of throw exception. Let's use it)
Small example
var arr = [12, "asd", 4];
arr.forEach(function(item) {
console.log(item - 0);
});
So you can check on NaN, don't forget that you should use special function isNaN()
var arr = [12, "asd", 4];
arr.forEach(function(item) {
if(isNaN(item - 0)) {
//do what you want with string
console.log("string");
};
else {
//do what you want with Number
console.log("number");
}
});

Embedded javascript not running in html file?

I am trying to make a function that provides the lowest multiplier of two integers. I've got some embedded JavaScript in my HTML file. It seems like the script isn't even running. It must be a problem with the function right? Because even when I did a simple direct return a*b function and it still didn't run. I am missing something here and can't find it.
<!-- language: lang-js -->
<!DOCTYPE html>
<html>
<body>
<p>The lowest multiple:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
var aArray = [];
var bArray = [];
for(var i = 2; true ; i++){
aArray.push(i*a);
bArray.push(i*b);
if(i%10 == 0){
for each(var item in aArray){
if(bArray.indexOf(item) >= 0){
return item;
}
}
if(i === 100){break;}
}
}
}
var a = prompt("");
var b = prompt("");
document.getElementById("demo").innerHTML = myFunction(a, b);
</script>
</body>
</html>
<!-- language: lang-js -->
<!DOCTYPE html>
<html>
<body>
<p>The lowest multiple:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
var aArray = [];
var bArray = [];
for(var i = 2; true ; i++){
aArray.push(i*a);
bArray.push(i*b);
if(i%10 == 0){
for(var item in aArray){
if(bArray.indexOf(aArray[item]) >= 0){
return aArray[item];
}
}
if(i === 100){break;}
}
}
}
var a = prompt("");
var b = prompt("");
document.getElementById("demo").innerHTML = myFunction(a, b);
</script>
</body>
</html>
for each(var item in aArray)
is not syntactically valid JavaScript. Array.prototype.forEach is a function you could use for iteration.

Categories