简体   繁体   English

Vanilla JS -.replace() 带有数组和循环

[英]Vanilla JS - .replace() with array and loop

I wrote myself a little script that converts English words to Elvish words.我给自己写了一个小脚本,可以将英语单词转换为精灵语单词。

 var clickMe = document.querySelector('#button-7993f34d'); clickMe.addEventListener('click', function (event) { setTimeout(function() { var checkSelect = document.querySelector("select"); // Lang checkSelect.innerHTML = checkSelect.innerHTML.replace('Tree', 'Adahl'); checkSelect.innerHTML = checkSelect.innerHTML.replace('Forest', 'Adahlen'); checkSelect.innerHTML = checkSelect.innerHTML.replace('Arrow', 'Assan'); }, 0); });
 <select> <option>Tree</option> <option>Forest</option> <option>Arrow</option> </select> <button id="button-7993f34d">click me</button>

Everything works fine.一切正常。 However, I would like to present the words in the form of an array.但是,我想以数组的形式呈现单词。 For example:例如:

langs = [
  {"eng": "Tree", "elf": "Adahl"},
  {"eng": "Forest", "elf": "Adahlen"},
  {"eng": "Arrow", "elf": "Assan"}
]

And not repeat it:不再重复:

 checkSelect.innerHTML = checkSelect.innerHTML.replace('Tree', 'Adahl');

This thread was closest to my solution: Using replace string method inside forEach However, I was unable to adapt it to my script.该线程最接近我的解决方案: 在 forEach 中使用替换字符串方法但是,我无法将其调整为我的脚本。

Is it possible in my case?在我的情况下可能吗? I tried to find a similar solution with the replace function.我试图通过替换 function 找到类似的解决方案。 Unfortunately, to no avail.不幸的是,无济于事。 Can you advise something?你能给点建议吗?

Still, I keep trying, if I find a solution before answering, I will definitely share it.不过,我一直在尝试,如果我在回答之前找到了解决方案,我一定会分享它。

Here is a very basic function that replaces occurrences of your english terms with elvish terms.这是一个非常基本的 function 用精灵术语替换您的英语术语的出现。

 function replaceText(text) { const langs = [ {"eng": "Tree", "elf": "Adahl"}, {"eng": "Forest", "elf": "Adahlen"}, {"eng": "Arrow", "elf": "Assan"} ]; let textToReturn = text; langs.forEach((word) => { textToReturn = textToReturn.replaceAll(word.eng, word.elf); }); return textToReturn; }; console.log(replaceText("My Tree is in the Forest"));

You could also do this with a switch statement.您也可以使用 switch 语句来执行此操作。

switch(wordInEnglish) {

    case "Tree": return "Adahl";
    
    case "Forrest": return "Adahlen";

    case "Arrow": return "Assan";

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM