1

How do I concatenate these strings to get value from a variable. I want to avoid eval as so many of you are not keen on its use.

function getLesson() {
    var lesson = "lesson" + localStorage.lessonNGS;
    document.getElementById("lessonNumber").innerHTML = "Lesson " + (eval(lesson + "." + number));
    document.getElementById("lessonTitle").innerHTML = (eval(lesson + "." + title));
    document.getElementById("lessonScore").src = (eval(lesson + "." + score));
    document.getElementById("mp3").src = (eval(lesson + "." + trackmp3));
    document.getElementById("ogg").src = (eval(lesson + "." + trackogg));
    document.getElementById("lessonTrack").load();
}

This works but I'm told it will cause me conflicts in some browsers.

0

2 Answers 2

3

Simply remove the eval

// Demo data
localStorage.setItem("lessonNGS",1);

var lesson1 = {
    number: "1",
    title: "Quarter Notes",
    score: "scores/01_quarternotes.jpg",
    trackmp3: "tracks/mp3/01_quarternotekeyexercises.mp3",
    trackogg: "tracks/ogg/01_quarternotekeyexercises.ogg"
};

function getLesson() {
    debugger;
    var lesson = window["lesson" + localStorage.lessonNGS];
    document.getElementById("lessonNumber").innerHTML = "Lesson " + lesson.number;
    document.getElementById("lessonTitle").innerHTML = lesson.title;
    document.getElementById("lessonScore").src = lesson.score;
    document.getElementById("mp3").src = lesson.trackmp3;
    document.getElementById("ogg").src = lesson.trackogg;
    document.getElementById("lessonTrack").load();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but the variable lesson isa string which is the name of a global variable that I want the first array of number from. So I want the value of lesson1("number") to add to the string to make "Lesson 1" for example.
i dont understand. the lesson is an array?
var lesson1 = {number:"1", title:"Quarter Notes", score:"scores/01_quarternotes.jpg", trackmp3:"tracks/mp3/01_quarternotekeyexercises.mp3", trackogg:"tracks/ogg/01_quarternotekeyexercises.ogg"};
Ok got you, updating the answer accordinaly
The variable lesson in the function is a carrier for the text "lesson1" made my appending the local storage variable, which is the lesson the student most recently used. There 39 lessons, whose variables are kept in a series of the above styled object arrays. The function fills the page with the title, music score and music track.
2

Javascript String.prototype.concat():

str.concat(string2, string3[, ..., stringN])

Example:

var hello = 'Hello, ';
console.log(hello.concat('Kevin', ' have a nice day.'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.