编程语言/Json/获取随即JSON对象:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的8个中间版本)
第1行: 第1行:
== 样本数据 ==
<syntaxhighlight lang="javascript">
var obj={"a":"aa","b":"bb","c":"cc","d":"dd"};
</syntaxhighlight>
== Math.random ==
== Math.random ==
1:
1:获取 JSON 随机对象
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
var obj={"a":1,"b":2,"c":3,"d":4}
function pickRandomProperty(obj) {
function pickRandomProperty(obj) {
     var result;
     var result;
第12行: 第14行:
     return result;
     return result;
}
}
pickRandomProperty(obj)</syntaxhighlight>
pickRandomProperty(obj);
==> "c"</syntaxhighlight>


2:
2:获取 JSON 对象集合随机数索引
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
var getRandom = function (min, max) {
var getRandom = function (min, max) {
   return Math.floor(Math.random() * (max - min) + min);
   return Math.floor(Math.random() * (max - min) + min);
};
};
getRandom(0, Object.keys(obj).length - 1)</syntaxhighlight>
getRandom(0, Object.keys(obj).length - 1);
==> 2</syntaxhighlight>
 
== Object.keys ==
== Object.keys ==
1:获得 JSON 对象随机值
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
var randomProperty = function (obj) {
var randomProperty = function (obj) {
第26行: 第32行:
     return obj[keys[ keys.length * Math.random() << 0]];
     return obj[keys[ keys.length * Math.random() << 0]];
};
};
randomProperty(obj);</syntaxhighlight>
randomProperty(obj);
==> "bb"</syntaxhighlight>
 
== hasOwnProperty ==
== hasOwnProperty ==
1:获得 JSON 随机对象
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
function randomProperty (obj) {
function randomProperty (obj) {
第38行: 第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>