【avalon】parseData

时间:2022-04-05 03:26:34
<div data-a="true" data-b="false" data-d="5" data-e="null"></div>
<input type="text" value="true">
<script>
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/
function parseData(data) {
//console.log(data)
try {
if (typeof data === "object")
return data
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
+data + "" === data ? +data :
rbrace.test(data) ? JSON.parse(data) : data
} catch (e) {
}
return data
} var dataset = document.querySelector('div').dataset
//console.log(parseData(dataset.a)) // "true" true
//console.log(parseData(dataset.b)) // "false" false
//console.log(parseData(dataset.c)) // undefined undefined
//console.log(dataset.e, parseData(dataset.e)) // "null" null
//console.log(parseData(dataset.d)) // "5" 5
</script>