everycode
everycode copied to clipboard
2014年12月12日 D6
/*
* 实现以下方法
* Object.prototype.random()
* 返回对象中的一个随机值
* e.g.
* var obj = {
* a: 1,
* b: {
* x: 2,
* y: 3
* },
* c: {
* z: {
* q: 4
* }
* }
* };
*
* obj.random(); // => 1 or 2 or 3 or 4 返回一个随机值
*
* obj = {};
*
* obj.random(); // => undefined
* Object.prototype.toRandomArray(): 返回一个随机排序的值的数组
*
* For example,
*
* var obj = {
* a: 1,
* b: {
* x: 2,
* y: 3
* },
* c: {
* z: {
* q: 4
* }
* }
* };
*
* obj.toRandomArray(); //返回一个随机值的数组[1, 2, 3, 4]
* obj = {};
* obj.toRandomArray(); //returns []
*/
Object.prototype.random = function() {
};
Object.prototype.toRandomArray = function() {
};
这些问题是考什么的?算法?
// 匹配JSON的值(数字或者字母开头,后面跟着的是, or })
var reg = /\w+(?=,|})/g
Object.prototype.random = function() {
return this.toRandomArray()[0];
};
Object.prototype.toRandomArray = function() {
return JSON.stringify(this).match(reg).sort(function(){
return Math.random() > 0.5 ? -1 : 1
});
};
// 测试用例
var obj = {
a: 1,
b: {
x: 2,
y: 3
},
c: {
z: {
q: 4
}
}
};
console.log(obj.random()); // 1 or 2 or 3 or 4 返回一个随机值
console.log(obj.toRandomArray()); // 返回一个随机值的数组[1, 2, 3, 4]
想写个匹配JSON值的正则表达式,然后做排序和随机,不严格,这样算是完成了题目吧。
function getV(obj,buf) {
if(typeof obj != 'object'){
console.error('this function need a "Object" argument');
return;
}
for(var o in obj){
if(typeof obj[o] == 'object'){
getV(obj[o],buf);
}
else if(typeof obj[o] != 'function'){
buf.push(obj[o]);
}
}
return buf;
}
var toRandomArray = function () {
var buf = getV(obj,[]);
buf.sort(function () {
return Math.random() > 0.5;
});
return buf;
};
var random =function () {
var arr = getV(obj,[]);
return arr[Math.floor(Math.random()*arr.length)];
};
console.log(toRandomArray());
console.log(random());
Object.prototype.toRandomArray = function () {
var obj = this,
arr = [],
loop = function (o,arr) {
for (var i in o) {
if (typeof o[i] === "function") break;
Object.prototype.toString.call(o[i]) === "[object Object]" ? loop(o[i],arr) : arr.push(o[i])
}
};
loop(obj,arr);
return arr.sort(function(){
return Math.random()>0.5
});
};
Object.prototype.random = function () {
var temp = this.toRandomArray();
return !temp.length?undefined:temp[0]
};