簡體   English   中英

如何在不使用eval的情況下將JS數組文字從HTML輸入字符串轉換為數組對象

[英]How to convert JS array literal from HTML input string to array object without using eval

我試圖在HTML文本輸入中接受JavaScript數組文字。

問題在於HTML文本輸入被捕獲為字符串,因此['name', 'who', 1]變為"['name', 'who', 1]"

我的意圖是讓以下示例產生相應的輸出。

"['river',"spring"]"        //  ["river","spring"]

"[{key:'value'},20,'who']"  //  [{"key":"value"},20,"who"]

解決此問題的方法是在下面的代碼片段中使用eval

 const form = document.querySelector('.form'); const inputField = document.querySelector('.input'); const btnParse= document.querySelector('.btn'); const out = document.querySelector('.out'); form.addEventListener('submit', (e)=> { e.preventDefault(); try { parsed = eval(inputField.value); if(Array.isArray(parsed)) { out.textContent = JSON.stringify(parsed); } else throw new Error('input is not a valid array' ); } catch(err) { out.textContent = `Invalid input: ${err.message}`; } }); 
  <form class="form">  <fieldset> <legend>Enter array to parse</legend>     <input class="input" type="text">     <input class="btn" type="submit" value="parse">  </fieldset> </form> <div>  <p class="out"> </p> </div> 


有什么其他方法可以在不使用eval的情況下將JavaScript數組文字HTML文本輸入轉換為JS數組對象?

JSON.parse("[1,2,3,4,5,6,5,6,7,78]")

JSON.parse("[\\"name\\", \\"who\\", 1]")將為您工作。

了解JSON.Parse 在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM