从Javascript中的JSON或XML列表中选择一个随机元素

时间:2018-03-08 11:34:37

标签: javascript json xml random

这是我正在使用的代码的简化。

<SCRIPT LANGUAGE="JavaScript">
var human = [

	
		{
            name: ["John","Peter","Sarah","Rose"],
            age: ["20","25","30"],
			nacionality: ["American","Welsh","Scotish","English"],
			country: ["USA","England","Wales","Scotland"],

		},

        {
        name: ["Renzo","Andrea","Monica","Tina"],
        age: ["20","25","30"],
		nacionality: ["Italian"],
		country: ["USA","England","Wales","Scotland"],

	},
    ],

    total = human.length,
    boton = document.getElementsByTagName("button")[0],
    parrafo = document.getElementsByTagName("p")[0];
	
    var p = Math.floor(Math.random() * total),
        pTotal = human[p].name.length,
        c = Math.floor(Math.random() * pTotal);
    	cTotal = human[p].age.length,
		ci=Math.floor(Math.random() *cTotal);
		ciTotal = human[p].nacionality.length,
		a=Math.floor(Math.random() *ciTotal);
		aTotal = human[p].country.length,
		cii=Math.floor(Math.random() *aTotal);
	
	document.write('Name: ' + human[p].name[c] +"</br>Age: "+ human[p].age[ci] + "</br>Nacionality: " + human[p].nacionality[a] +"</br>Country: " + human[p].country[cii]); 
</SCRIPT>

我会有很多像这样的戒指。还有一些,例如国家,我想从一个外部列表中选择。我不想单独更换每个戒指。

我不会使用服务器,也不会使用PHP。我需要从JSON或XML中选择该元素。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我已将您的属性名称更改为复数,因此它们反映了我们正在处理某种列表的事实。

&#13;
&#13;
function sample(arr){
  return arr.length? 
    arr[Math.floor(Math.random() * arr.length)]: 
    undefined;
}

var humans = [
  {
    names: ["John", "Peter", "Sarah", "Rose"],
    ages: ["20", "25", "30"],
    nationalities: ["American", "Welsh", "Scotish", "English"],
    countries: ["USA", "England", "Wales", "Scotland"],
  },

  {
    names: ["Renzo", "Andrea", "Monica", "Tina"],
    ages: ["20", "25", "30"],
    nationalities: ["Italian"],
    countries: ["USA", "England", "Wales", "Scotland"],
  },
];

var group = sample(humans);
container.innerHTML = [
  "Name: " +        sample(group.names),
  "Age: " +         sample(group.ages),
  "Nacionality: " + sample(group.nationalities),
  "Country: " +     sample(group.countries)
].join("<br>");
&#13;
<div id="container"></div>
&#13;
&#13;
&#13;