-
Notifications
You must be signed in to change notification settings - Fork 26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2014年12月12日 D6 #25
Labels
Comments
这些问题是考什么的?算法? |
// 匹配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]
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: