编程语言/Json/获取随即JSON对象:修订间差异
来自康健生活
小 Kangkk移动页面Json/获取随即JSON对象至编程语言/Json/获取随即JSON对象 |
|||
| (未显示同一用户的5个中间版本) | |||
| 第36行: | 第36行: | ||
== hasOwnProperty == | == hasOwnProperty == | ||
1:获得 JSON 随机对象 | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
function randomProperty (obj) { | function randomProperty (obj) { | ||
| 第46行: | 第47行: | ||
return keys[keys.length * Math.random() << 0]; | return keys[keys.length * Math.random() << 0]; | ||
} | } | ||
randomProperty(obj);</syntaxhighlight> | 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> | |||