gpt4 book ai didi

javascript - 将Javascript字符串转换为文字数组

转载 作者:行者123 更新时间:2023-12-04 02:15:07 24 4
gpt4 key购买 nike

在 python 中存在 ast.literal_eval(x) 如果 x 是 "['a','b','c']"然后它将返回列表 ['a','b','c'] . Javascript/jQuery 中是否存在类似的东西,我可以将存储在表格单元格中的数组作为 [x,y,z] 并将其转换为文字 JavaScript 数组?

我宁愿避免任何可能容易出错的复杂解决方案,因为可能涉及拆分逗号或转义字符。

编辑:我应该给出一些更好的例子:
['la maison', "l'animal"]是一个遇到错误的示例,因为替换单引号或双引号可能会导致问题,因为无法保证它会是哪个。

最佳答案

可以利用 String.prototype.replace() JSON.parse() .
请参阅下面的粗略示例。

// String.prototype.replace() + JSON.parse() Strategy.
const input = "['a','b','c']" // Input.
const array = JSON.parse(input.replace(/'/g, '"')) // Array.
console.log(array) // Proof.

虽然,鉴于您的更新/更复杂的用例, eval() 可能更合适。

// eval() Strategy.
const input = `['la maison', "l'animal"]` // Input.
const dangerousarray = eval(input) // Array.
const safearray = eval(`new Array(${input.replace(/^\[|\]$/g, '')})`)
console.log(dangerousarray) // Proof.
console.log(safearray) // Proof.

但是,MDN 文档不鼓励使用 eval()。由于安全/速度缺陷。
因此,人们可能会选择类似于以下的方法:

// Heavy Replacement Strategy.
const input = `['la maison', 'l\'animal']` // Input.
const array = input
.replace(/^\[|\]$/g, '') // Remove leading and ending square brackets ([]).
.split(',') // Split by comma.
.map((phrase) => // Iterate over each phrase.
phrase.trim() // Remove leading and ending whitespace.
.replace(/"/g, '') // Remove all double quotes (").
.replace(/^\'|\'$/g, '') // Remove leading and ending single quotes (').
)
console.log(array) // Proof.

关于javascript - 将Javascript字符串转换为文字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com