我收到以下輸入:
const myString = "['one', 'two']";
當我運行以下命令時:
console.log(typeof myString);
我明白了string
這是有道理的,因為這是一個字串輸入。輸入型別超出了我的控制,我必須將其作為 typeof 字串接收。
但是,我想將此字串轉換為正式的字串陣列。
例如:
const myArray = ['one', 'two'];
所以,當我運行時:
console.log(typeof myArray);
我明白了object。
我試過了JSON.parse(),JSON.stringify但沒有運氣。
我的問題的基礎是如何(在 JavaScript 中)將字串陣列轉換為字串陣列?
uj5u.com熱心網友回復:
JSON.parse 如果 JSON 不是無效的,它將起作用。如評論中所述,字串必須格式化為'["1", "2"]'.
如果您無法控制格式,您可以手動決議它:如果字串不包含引號,您可以使用#replaceAll("'", '"').
如果您有需要覆寫的邊緣情況,json5可能會有所幫助:JSON5.parse(str)一旦您通過 NPM 或 unpkg 加載了腳本
uj5u.com熱心網友回復:
JSON 僅識別" ". 要決議它,您需要使用雙引號而不是單引號。
const myString = "['one', 'two']";
// change to
const myString = '["one", "two"]';
這是一個例子:
// Not working
const Str = "['one', 'two']";
console.log(Str); // ['one', 'two']
console.log(typeof Str); // string
JSON.parse(Str); // SyntaxError: Unexpected token ' in JSON at position 1
// Working example:
const myString = '["one", "two"]';
console.log(myString); // ["one", "two"]
console.log(typeof myString); // string
const myArray = JSON.parse(myString);
console.log(myArray); // [ 'one', 'two' ]
console.log(typeof myArray); // object
如果您需要更改'為"僅使用replace。
uj5u.com熱心網友回復:
const myArray = ['one', 'two'];
let str = myArray.toString();
console.log(str);//one,two
console.log(typeof str)//string
let srr = str.split(",");
console.log(srr);//[ 'one', 'two' ]
console.log(typeof srr)//object same as that of myArray
上面的變數 myArray 持有一個陣列。為了將陣列轉換為字串,myArray.toString() 中有一個內置方法。現在要將陣列轉換為字串,我們將使用如上所示的拆分方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482997.html
標籤:javascript 数组 目的 javascript 对象
