如何在包含模板文字(Javascript)的数组中存储字符串? [英] How to store strings in an array that include Template Literals (Javascript)?

查看:50
本文介绍了如何在包含模板文字(Javascript)的数组中存储字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在一个数组中存储很多文本(因此我可以轻松地使用一个值将其提取出来).问题出在我想使用模板文字的字符串之内,因此该字符串根据输入而变化(例如,一旦他们添加了名称,它就会使用其名称.

I’m trying to store a lot of text in an array (so I can easily pull it out using a value). The issue is within the strings I’d like to use template literals so the string changes depending on input (e.g. once they’ve added their name, it uses their name.

如果我在函数中包含字符串,那么我可以正常工作.例如:

I can get this working no problem if I include the string in the function. For example:

textbox.textContent =  `what does ${nameTemp} do?`;

这没问题,它将"nameTemp"更改为用户输入的内容.但这下面没有!它总是返回"tim"作为名称("nameTemp"的默认值)

That works no problem, it changes "nameTemp" to what the user inputted. But this below does not! It always returns "tim" as the name (the default value for "nameTemp")

textbox.textContent2 = Title[1]; 

在下面的代码中,您可以在函数saveName()中看到第一行(带有包含模板文字的完整字符串)可以正常工作.但是下面的行使用数组中的字符串(包含模板文字)不会更新,它使用默认字符串'tim'.我究竟做错了什么?我如何最好地将字符串存储在具有可更改元素的数组中?在此先感谢您的任何建议.

You can see in the code below in the function saveName() that the first line (with the full string including the template literal does work. But the line below, using the string from the array (with the template literal in) does not update. It uses the default string ‘tim’. What am I doing wrong? How can i best store strings in an array that have chanagable elements? Thanks in advance for any suggestions.

var nameTemp = `tim`;

let Title = [];
Title[0] = "What are you called?";
Title[1] = `what does ${nameTemp} do?`;

const input = document.createElement('input');
input.type = "text";
input.id ="nameText";
input.className +='inputStyle';

 function addNameInput()
    {
     container.appendChild(input);
    }

 function saveName()
    {
     if (nameText.value !== null)
     {
     nameTemp = nameText.value;
     textbox.textContent =  `what does ${nameTemp} do?`; //This works, it displays the inputed name
     textbox.textContent2 = Title[1];  // This will always display 'tim'
     nameText.parentNode.removeChild(nameText);
     incrementState();
     }
    }

推荐答案

首次创建Javascript模板字符串时会对其进行评估,并且它们不会进行神奇的更新. Title [1] "tim" 初始化,即使更改了 nameTemp 变量,它也将保持不变.如果要将模板字符串存储在数组中,则可以存储一个返回模板字符串的函数,例如:

Javascript template strings are evaluated when you first create them, and they don't magically update. Title[1] is initialized with "tim", and even after you change the nameTemp variable it'll remain the same. If you want to store template strings in an array then you can store a function that returns a template string, like:

Title[1] = () => `what does ${nameTemp} do?`;

然后您可以通过获取值

textbox.textContent2 = Title[1]();

这篇关于如何在包含模板文字(Javascript)的数组中存储字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆