我有一个我无法解决的问题。我需要做这样的事情:
var text = "[{\"VID\":\"115\"},{\"VID\":\"119\"},{\"VID\":\"116\"},...]";
我想根据“text”变量获得以下结果:
var VIDs = ["115", "119", "116", ...];
答案 0 :(得分:2)
我认为,您可以使用简单的正则表达式来提取所有数值
function makeTable(leaderBoard) {
var table = document.createElement('table');
var row = document.createElement('tr');
for (var i = 0; i < leaderBoard[0].length; i++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[0][i];
row.appendChild(cell);
}
var cell = document.createElement('td');
cell.textContent = "Total: " + leaderBoard[1];
row.appendChild(cell);
table.appendChild(row);
document.getElementById('leaderBoard').appendChild(table);
}
var userCards = ["Card 1", "Card 2", "Card 3"];
var userTotal = 10;
makeTable([userCards, userTotal]);
var text = "[{\"VID\":\"115\"},{\"VID\":\"119\"},{\"VID\":\"116\"}]";
var vids = text.match(/\d+/g);
snippet.log(JSON.stringify(vids))
使用JSON处理的另一种解决方案是
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
var text = "[{\"VID\":\"115\"},{\"VID\":\"119\"},{\"VID\":\"116\"}]";
var vids = JSON.parse(text).map(function(obj) {
return obj.VID;
});
snippet.log(JSON.stringify(vids))