我真的很新本,因此我的术语可能是穷人,问我澄清,如果你需要。很抱歉,如果这是一个基本的问题。这里是我的问题的一个示例:
var post1title = "example title 1";
var post1text = "example text 1";
var post2title = "example title 2";
var post2text = "example text 2";
function update() {
setText("titleBox", post1title);
setText("bodyBox", post1text);
我的目标是使功能更新()有一个参数,允许在一个文本框中的文本是要么,例如,post1title或post2title。
我想要做类似的东西给您,当变量都参与其中,如下所示的字符串做什么:
console.log("User has set the variable post1title to: " + post1title);
// prints "User has set the variable post1title to: example title 1" to the debug console
它似乎并不像你可以调用变量时做同样的事情,但。我试图做同样的,你会与字符串(其中“n”是一个数字1-2):
var post1title = "example title 1";
var post1text = "example text 1";
var post2title = "example title 2";
var post2text = "example text 2";
function update(n) {
setText("titleBox", post + n + title);
setText("bodyBox", post + n + text);
这显然全文加入三个变量在一起。是这样的可能吗?
您可以将值存储为一个普通的物体或Map
的性能和使用计算的属性名称或括号符号得到相应的价值。
您还可以调整预期的参数的顺序。
const o = {
post1title: "example title 1",
post1text: "example text 1",
post2title: "example title 2",
post2text: "example text 2"
}
function update(p, t, n) {
console.log(o[p + n + t])
}
update('post', 'title', 1);
你可以使用一个对象与bracket notation做一些类似的。这样,你的对象将持有钥匙,而此时他们的关联值。
见下面例子:
var options = {
post1title: "example title 1",
post1text: "example text 1",
post2title: "example title 2",
post2text: "example text 2"
}
function update(n) {
setText("titleBox", options["post"+ n + "title"]);
setText("bodyBox", options["post" + n + "text"]);
}
function setText(id, txt) {
document.getElementById(id).textContent = txt;
}
update(1)
<h2 id="titleBox"></h2>
<p id="bodyBox" ></p>
或者,另一种方法是使用一个构造函数如下所示:
var post1title = "example title 1";
var post1text = "example text 1";
var post2title = "example title 2";
var post2text = "example text 2";
function update(n) {
setText("titleBox", Function("return post"+ n + "title")());
setText("bodyBox", Function("return post"+ n + "text")());
}
function setText(id, txt) {
document.getElementById(id).textContent = txt;
}
update(1);
<h2 id="titleBox"></h2>
<p id="bodyBox" ></p>
这是一个反模式,至少可以说,但如果你真的想这样做(和你不这样做,但很可惜):
function update(n) {
setText("titleBox", eval("post" + n + "title"));
...
......而且,它has higher performance than using a Function() constructor。不过,eval()
是不好的做法。
这可能是最好的变量转换成一个对象。这种结构模拟最好从数据库例如获取真实的数据。而我使用的Template Literals内console.log
在一个更简单的方法相结合的字符串和变量
var posts = {
"title": {
"1": "example title 1",
"2": "example title 2",
},
"text": {
"1": "example text 1",
"2": "example text 2",
}
}
function update(part, n) {
/* setText("titleBox", post1title);
setText("bodyBox", post1text); */
console.log(`User has set the variable post${n}${part} to: ${posts[part][n]} `);
}
update('title', '1')
update('title', '2')
update('text', '1')
update('text', '2')