编程语言/Json/获取随即JSON对象:修订间差异
来自康健生活
创建页面,内容为“== Math.random == <syntaxhighlight lang="javascript"> var a={"a":1,"b":2} function pickRandomProperty(obj) { var result; var count = 0; for (var prop in…” |
小 Kangkk移动页面Json/获取随即JSON对象至编程语言/Json/获取随即JSON对象 |
||
| (未显示同一用户的10个中间版本) | |||
| 第1行: | 第1行: | ||
== 样本数据 == | |||
<syntaxhighlight lang="javascript"> | |||
var obj={"a":"aa","b":"bb","c":"cc","d":"dd"}; | |||
</syntaxhighlight> | |||
== Math.random == | == Math.random == | ||
1:获取 JSON 随机对象 | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
function pickRandomProperty(obj) { | function pickRandomProperty(obj) { | ||
var result; | var result; | ||
| 第11行: | 第14行: | ||
return result; | return result; | ||
} | } | ||
pickRandomProperty( | pickRandomProperty(obj); | ||
==> "c"</syntaxhighlight> | |||
2:获取 JSON 对象集合随机数索引 | |||
<syntaxhighlight lang="javascript"> | |||
var getRandom = function (min, max) { | |||
return Math.floor(Math.random() * (max - min) + min); | |||
}; | |||
getRandom(0, Object.keys(obj).length - 1); | |||
==> 2</syntaxhighlight> | |||
== Object.keys == | |||
1:获得 JSON 对象随机值 | |||
<syntaxhighlight lang="javascript"> | |||
var randomProperty = function (obj) { | |||
var keys = Object.keys(obj) | |||
return obj[keys[ keys.length * Math.random() << 0]]; | |||
}; | |||
randomProperty(obj); | |||
==> "bb"</syntaxhighlight> | |||
== hasOwnProperty == | |||
1:获得 JSON 随机对象 | |||
<syntaxhighlight lang="javascript"> | |||
function randomProperty (obj) { | |||
var keys = []; | |||
for (var prop in obj) { | |||
if (obj.hasOwnProperty(prop)) { | |||
keys.push(prop); | |||
} | |||
} | |||
return keys[keys.length * Math.random() << 0]; | |||
} | |||
randomProperty(obj); | |||
==> "b"</syntaxhighlight> | |||
2:获得 JSON 对象随机值 | |||
<syntaxhighlight lang="javascript"> | |||
function randomProperty (obj) { | |||
var newObj = {}, total = 0;; | |||
for(var key in obj){ | |||
if(obj.hasOwnProperty(key)){ | |||
newObj[total++] = key; | |||
} | |||
} | |||
var _index = ~~(Math.random() * total); | |||
return obj[newObj[_index]]; | |||
} | |||
randomProperty(obj); | |||
==> "cc"</syntaxhighlight> | |||