如何在不使用eval的情况下连接字符串?

时间:2015-12-29 07:13:12

标签: javascript

如何连接这些字符串以从变量中获取值。我想避免使用eval,因为很多人都不热衷于使用它。

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();
}

这有效,但我告诉它会在某些浏览器中引起冲突。

2 个答案:

答案 0 :(得分:3)

只需删除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();
}

答案 1 :(得分:2)

Javascript String.prototype.concat()

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

示例:

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