I have an array of objects
var event1Array {
name: wedding;
time: ["10:00am", "12:00pm"];
}
var event2Array {
name: housewarming;
time: ["7:00pm", "9:00pm"]
}
var eventArray = [event1Array, event2Array];
I want to loop through using just two loops (inner and outer) using an alert like this
alert("attend a " + eventArray.name + " starting " + theEvent.time)
But my event info keeps printing twice like
attend a wedding starting 10am,
attend a wedding starting 12pm
attend a housewarming starting 7pm
attend a housewarming starting 9pm
here's the complete code
var event1Array
{
name: wedding;
time: ["10:00am", "12:00pm"];
}
var event2Array
{
name: housewarming;
time: ["7:00pm", "9:00pm"];
}
var div = document.getElementById("events");
var eventArray = [event1Array, event2Array];
for (var i = 0; i < eventArray.length; i++)
{
var theEvent = eventArray[i];
for (j = 0; j < theEvent.time.length; j++)
{
console.log("Attending a wedding" + theEvent.name + "starting" + theEvent.time[j]);
}
}
They aren't Arrays. event1Array and event2Array are actually Objects, so you don't want to loop through them. You should only be looping through the eventArray.
for (var i = 0, len = eventArray.length; i < len; i++) {
alert("attend a " + eventArray[i].name + " starting " + eventArray[i].time[0]);
}
Here is a working jsfiddle...
try this
alert("attend a " + eventArray.name + " starting " + theEvent.time[0])
Related
I am trying to the splice method but it is not working properly want to delete one user but it is deleting 2.
Also want to add the binary search button
this is the requirement for binary search
Replace the sequential access algorithm to operate on the arrays with a binary search algorithm.
To implement this, the array’s data must be sorted. You may refer to an online example available at Array.prototype.sort() to learn about sorting data in arrays.
function Display_Athlete() {
var text = "<hr/>";
for (let i = 0; i < athlete_name.length; i++) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
document.getElementById("message").innerHTML = text;
}
//Created function to remove the user
function Remove_Athlete() {
var person = prompt("Enter the name to remove the Athlete");
for (let i = 0; i < athlete_name.length; i++) {
athlete_name.splice(person - 1, 1);
athlete_height.splice(person - 1, 1);
alert(" Athlete_name " + athlete_name + " Athlete_height " + athlete_height + " is removed ");
}
}
//Create the function to find the user
function Find_Athlete() {
var person = prompt("Enter the name to Find the Athlete");
var text = "";
for (let i = 0; i < athlete_name.length; i++) {
if (athlete_name[i] == person) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
}
document.getElementById("message").innerHTML = text;
if (text == "")
alert(`${person} Invalid Athlete name`);
return "";
}
function Binary_Search(){
}
As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;
I want to show up the names of the members of an array "path" in my console.
console.log("start: ", path[0].name, "second: ", path[1].name, "third: ", path[2]name, ....)
But the problem is, that my array always changes it's size (clicking algorithm), that means sometimes it has the lenght 4 or sometimes 8 ect.
How can i adjust the console.log code to this dynamic array?
Thanks so much!
Try
path.forEach((each, i)=>{
console.log ("item" + i+ ':' + each.name );
})
Something like this:
var path = ['Prit', 'Bab', 'Nav']
var item = ["first","second", "third"];
for (i = 0; i < path.length;i++){
console.log(item[i] + ":" + path[i])
}
Try something like this for single line result set ...
var result = "";
for (var i = 0, len = path.length; i < len; i++) {
if (i !== 0) {
result += ", ";
}
result += (i + 1) + ": " + path[i].name;
}
console.log(result);
you could use a for loop here , ie,
for (var i=0;i<path.length;i++) {
console.log("item no "+ i +": " + path[i]);
}
/* Console Array */
var consoleArray = new Array;
/* Names */
var path = [
{name: 'bob'},
{name: 'jimmy'},
{name: 'chris'},
{name: 'alexander'},
{name: 'mark'}
];
/* Loop */
for(var i = 0; i < path.length; i++) {
consoleArray.push((i + 1) + ': ' + path[i].name);
}
/* Console Log */
console.log(consoleArray.join("\n"));
With ES6, you could use spread syntax ....
var path = [{ name: 'Jo'}, { name: 'John'}, { name: 'Jane'}];
console.log(...path.map((a, i) => (i ? i + 1 : 'Start') + ': ' + a.name));
I have a website that loads in songs for the user to play them. This method "loadSongs()" basically takes all the songs from a file input and is called "onchange" of the file input. I simply can't get the file names to get pushed into my string array called: "songs". Would appreciate any help, here is my code:
function loadSongs() {
var x = document.getElementById("file");
var songs = new Array();
if (x.files.length != 0) {
for (var i = 0; i < x.files.length; i++) {
var file = x.files[i];
songs.push(file.name);
}
}
for (var j = 0; j < songs.length; j++) {
alert("song #" + i + ": " + songs[i]);
}
}
I can successfully access the all the files in the first for loop because when I did "alert(file.name)" in the first for loop, it worked fine. I just can't get them into the string array unfortunately.
The problem is not the push method, it is your alert parameters.
In the second loop:
for (var j = 0; j < songs.length; j++) {
alert("song #" + i + ": " + songs[i]);
}
You have "song #" + i + ": " + songs[i], but your loop is using j as the counter variable. Just change i to j.
for (var j = 0; j < songs.length; j++) {
alert("song #" + j + ": " + songs[j]);
}
I have made a questionnaire that asks 10 questions, however I would like to add a small timer to show how long the user has taken in seconds. I have looked online for help however I always have some issue with displaying the timer itself.
Here's my program:
<html>
<head>
<title>Best Gaming Quiz Ever!</title>
</head>
<body>
<h1>Gaming Quiz</h1>
We have made 10 questions for you to answer about gaming and gaming companies. Do your best, and don't guess,
<br>it's really not that difficult. Also, try not to be a cheating noob and click "check answer" before you make your choice!
<br>Challenge yourself, and have fun!
<h2>Your mission:</h2>
Just pick the correct answer, duh, it's a quiz, what else?
<br>
<br>
<script type="text/javascript">
var allowPeeking = 1
var allowDoOvers = 1
questions = new Array();
// Q & A questions set as Arrays below
// Questions are used first
// Correct answer is followed with "right"
// all wrong ones with ""
questions[0] = ["Which are gaming companies?:", "Valve", "right", "Microsoft", "", "Apple", "", "FedEx", ""]
questions[1] = ["Which is a game?:", "Micrsoft Word", "", "Piskel", "", "Dota 2", "right", "csTimer.net", ""]
// To display question array list
for (i = 0; i < questions.length; i++) {
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "")
questions[i][j] = ("w" + i) + j
if (questions[i][j] == "right")
questions[i][j] = "right" + i
}
}
var ie = document.all
// diplays answer holder when button is pressed
function showAnswer(el, ans) {
ie ? ie[el].innerHTML = 'The answer is: ' + ans : document.getElementById(el).innerHTML = 'The answer is: ' + ans
}
function addup() {
var q, right, statement, total = 0
quizQuests = new Array();
for (i = 0; i < questions.length; i++)
quizQuests[i] = 0
if (document.forms.quiz.q0['right0']) {
for (i = 0; i < questions.length; i++) {
q = "q" + i
right = "right" + i
// takes away 1 if incorrect!
if (document.forms.quiz[q][right].checked)
quizQuests[i] += -1
}
} else if (document.getElementById) {
for (i = 0; i < questions.length; i++) {
right = "right" + i
// adds 2 if correct!
if (document.getElementById(right).checked)
quizQuests[i] = 2
}
} else
return;
for (i = 0; i < questions.length; i++)
total += quizQuests[i]
// Displays end score (Attempted to get percentage but remove as it wouldn't calculate correctly)
statement = 'You scored ' + total + ' points out of 20'
ie ? ie.results.innerHTML = statement : document.getElementById('results').innerHTML = statement
}
function clearR() {
ie ? ie.results.innerHTML = '' : document.getElementById('results').innerHTML = ''
for (i = 0; i < questions.length; i++)
if (allowPeeking)
ie ? ie["ans" + i].innerHTML = '' : document.getElementById("ans" + i).innerHTML = ''
window.scrollTo(0, 0);
}
document.write('<hr><form name="quiz">')
var correct, answersString
// displaying answers & checking correct / wrong choices
for (i = 0; i < questions.length; i++) {
answersString = ''
for (k = 1; k < questions[i].length; k += 2)
answersString += '<input id="' + questions[i][(k + 1)] + '" type="radio" unchecked name="q' + i + '"><label for="' + questions[i][(k + 1)] + '">' + questions[i][k] + '</label><br>'
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "right" + i)
correct = questions[i][j - 1]
}
with(document) {
write('Question ' + (i + 1) + ':<br><br>')
write(questions[i][0] + '<br>')
write(answersString)
// simply displays answer ("right" - 1)
if (allowPeeking)
write('<input class="chkans" type="button" value="Check Answer" onclick="showAnswer(\'ans' + i + '\',\'' + correct + '\')"> <span id="ans' + i + '" class="chkans"></span><br> ')
write('<br>')
}
}
with(document) {
// calls addup function
write('<hr><br>')
write('<input type="button" value="See Score" onclick="addup()"> <span id="results"></span><br> <br>')
// calls clearR function
if (allowDoOvers)
write('<input type="button" value="Start Again" onclick="reset();clearR()">')
write('</form>')
}
</script>
</body>
</html>
Appreciate any help given.
Check below answer. The timer will stop when you click the button See Score.
<html>
<head>
<title>Best Gaming Quiz Ever!</title>
</head>
<body>
<h1>Gaming Quiz</h1>
We have made 10 questions for you to answer about gaming and gaming companies. Do your best, and don't guess,
<br>it's really not that difficult. Also, try not to be a cheating noob and click "check answer" before you make your choice!
<br>Challenge yourself, and have fun!
<h2>Your mission:</h2>
Just pick the correct answer, duh, it's a quiz, what else?
<br>
<br>
<hr>
<br>
<b>Time taken:</b> <span id="timer">0</span> seconds
<br>
<br>
<script type="text/javascript">
var t = 0;
var runTimer = setInterval(function() {
t++;
document.getElementById("timer").innerHTML = t;
}, 1000);
var allowPeeking = 1
var allowDoOvers = 1
questions = new Array();
// Q & A questions set as Arrays below
// Questions are used first
// Correct answer is followed with "right"
// all wrong ones with ""
questions[0] = ["Which are gaming companies?:", "Valve", "right", "Microsoft", "", "Apple", "", "FedEx", ""]
questions[1] = ["Which is a game?:", "Micrsoft Word", "", "Piskel", "", "Dota 2", "right", "csTimer.net", ""]
// To display question array list
for (i = 0; i < questions.length; i++) {
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "")
questions[i][j] = ("w" + i) + j
if (questions[i][j] == "right")
questions[i][j] = "right" + i
}
}
var ie = document.all
// diplays answer holder when button is pressed
function showAnswer(el, ans) {
ie ? ie[el].innerHTML = 'The answer is: ' + ans : document.getElementById(el).innerHTML = 'The answer is: ' + ans
}
function addup() {
clearInterval(runTimer);
var q, right, statement, total = 0
quizQuests = new Array();
for (i = 0; i < questions.length; i++)
quizQuests[i] = 0
if (document.forms.quiz.q0['right0']) {
for (i = 0; i < questions.length; i++) {
q = "q" + i
right = "right" + i
// takes away 1 if incorrect!
if (document.forms.quiz[q][right].checked)
quizQuests[i] += -1
}
} else if (document.getElementById) {
for (i = 0; i < questions.length; i++) {
right = "right" + i
// adds 2 if correct!
if (document.getElementById(right).checked)
quizQuests[i] = 2
}
} else
return;
for (i = 0; i < questions.length; i++)
total += quizQuests[i]
// Displays end score (Attempted to get percentage but remove as it wouldn't calculate correctly)
statement = 'You scored ' + total + ' points out of 20'
ie ? ie.results.innerHTML = statement : document.getElementById('results').innerHTML = statement
}
function clearR() {
ie ? ie.results.innerHTML = '' : document.getElementById('results').innerHTML = ''
for (i = 0; i < questions.length; i++)
if (allowPeeking)
ie ? ie["ans" + i].innerHTML = '' : document.getElementById("ans" + i).innerHTML = ''
window.scrollTo(0, 0);
}
document.write('<hr><form name="quiz">')
var correct, answersString
// displaying answers & checking correct / wrong choices
for (i = 0; i < questions.length; i++) {
answersString = ''
for (k = 1; k < questions[i].length; k += 2)
answersString += '<input id="' + questions[i][(k + 1)] + '" type="radio" unchecked name="q' + i + '"><label for="' + questions[i][(k + 1)] + '">' + questions[i][k] + '</label><br>'
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "right" + i)
correct = questions[i][j - 1]
}
with(document) {
write('Question ' + (i + 1) + ':<br><br>')
write(questions[i][0] + '<br>')
write(answersString)
// simply displays answer ("right" - 1)
if (allowPeeking)
write('<input class="chkans" type="button" value="Check Answer" onclick="showAnswer(\'ans' + i + '\',\'' + correct + '\')"> <span id="ans' + i + '" class="chkans"></span><br> ')
write('<br>')
}
}
with(document) {
// calls addup function
write('<hr><br>')
write('<input type="button" value="See Score" onclick="addup()"> <span id="results"></span><br> <br>')
// calls clearR function
if (allowDoOvers)
write('<input type="button" value="Start Again" onclick="reset();clearR()">')
write('</form>')
}
</script>
</body>
</html>