编程语言/Json/获取随即JSON对象:修订间差异
来自康健生活
| 第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"> | ||
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 == | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
2020年5月13日 (三) 13:02的版本
样本数据
var obj={"a":"aa","b":"bb","c":"cc","d":"dd"};
Math.random
1:获取 JSON 对象
function pickRandomProperty(obj) {
var result;
var count = 0;
for (var prop in obj)
if (Math.random() < 1/++count)
result = prop;
return result;
}
pickRandomProperty(obj);
==> "c"
2:获取 JSON 对象集合随机数索引
var getRandom = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
getRandom(0, Object.keys(obj).length - 1);
==> 2
Object.keys
var randomProperty = function (obj) {
var keys = Object.keys(obj)
return obj[keys[ keys.length * Math.random() << 0]];
};
randomProperty(obj);
hasOwnProperty
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);
No categories