Im trying to make a weird online program but im having trouble.
Here is my code:
function name() {
var titles = ["titles", "titles", "titles", "titles", "titles", "titles"];
var randFor = Math.random();
randFor = 7 * randFor;
randFor = Math.floor(randFor);
var finished = [];
var arraySpot = 0;
var newVal;
var newValSpot = 0;
newVal = finished[newValSpot];
for (i = 0; i < randFor; i++) {
var randArray = Math.random();
randArray = 7 * randArray;
randArray = Math.floor(randArray);
finished.push[arraySpot] = titles[randArray];
arraySpot++;
newValSpot++;
newVal = " " + finished[newValSpot];
}
document.getElementById("gen").innerHTML =newVal;
}
Basically, what im trying to do is take an array of words, and convert it to a variable and display it in this tag:
<div id="gen"></div>
But every time it gives me "undefined" with a space in front of it?
Any help is appreciated, sorry for being such a noob in JS.
UPDATE I have revised the code, i no longer get "undefined" but now i get nothing?
function name() {
var titles = ["titles", "titles", "titles", "titles", "titles", "titles"];
var randFor = Math.random();
randFor = 7 * randFor;
randFor = Math.floor(randFor);
var newVal;
newVal = title[0];
for (i = 0; i < randFor; i++) {
var randArray = Math.random();
randArray = 7 * randArray;
randArray = Math.floor(randArray);
newVal = " " + titles[randArray];
}
document.getElementById("gen").innerHTML = newVal;
}
1 Answer 1
hope this is useful
newVal = finished[newValSpot];At this time,finishedis still empty array, so you got anundefinedvalue.finished.push[arraySpot] = titles[randArray];Please check this for push method.newVal = " " + titles[randArray];This will assignnewVala new value, I guess you want to do this.newVal = " " + titles[randArray];
Update
var titles = ["titles", "titles", "titles", "titles", "titles", "titles"];Thetitleslength is 6, not 7, you should add one more "titles" intotitles.newVal = " " + titles[randArray];The same issue, I think you want to do this.newVal = newVal + " " + titles[randArray];
function name() {
// Add one more "titles" in this array.
var titles = ["titles", "titles", "titles", "titles", "titles", "titles", "titles"];
var randFor = Math.random();
randFor = 7 * randFor;
randFor = Math.floor(randFor);
var newVal;
newVal = titles[0];
for (i = 0; i < randFor; i++) {
var randArray = Math.random();
randArray = 7 * randArray;
randArray = Math.floor(randArray);
newVal = newVal + " " + titles[randArray];
}
document.getElementById("gen").innerHTML = newVal;
}
name();
<div id="gen"></div>
answered May 17, 2016 at 0:21
Haizhou Liu
4912 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Colin Cappetto
Thank you so much, this fixed everything and now i know what to do in the future, im new to JS so this is a ton of help! Thanks!
lang-js