使用JavaScript编写一个对字符串、数组、对象随机打乱顺序的功能。
代码如下:
/**
* 获取对象的键名
* @param {Object|Array|String|Number} obj
* @param {number} opt 默认返回自有可枚举属性,值为-1时返回所有自有属性,值为1时返回所有可枚举属性
* @return {boolean|Array}
*/
function getKeys(obj, opt) {
var op = Object.prototype, type = op.toString.call(obj), S = "[object String]", N = "[object Number]", key, key_list = [];
if ((obj !== null && obj !== undefined && typeof obj !== "boolean" && typeof obj === "object") || type === "[object Function]" || type === S || type === N) {
(type === S || type === N) && (obj = String(obj).split(""));
if (opt === -1) {
return Object.getOwnPropertyNames(obj);
}
for (key in obj) {
if (opt) {
key_list.push(key);
} else {
op.hasOwnProperty.call(obj, key) && key_list.push(key);
}
}
return key_list;
}
return false;
}
/**
* 随机打乱顺序
* @param {Object|Array|string|number} data
* @param {boolean|number} opt 值为1是保持原先的键值关系
* @return {*}
*/
function shuffle(data, opt) {
var exp = ["^\\[object\\s(", "Object|Array|String|Number", ")\\]$"], op = Object.prototype, type = op.toString.call(data), reg, reg_str, key_list;
reg = new RegExp(exp.join(""), "i"), exp[1] = "String|Number", reg_str = new RegExp(exp.join(""), "i");
if (!reg.test(type)) {
return data;
}
reg_str.test(type) && (data = String(data).split(""));
key_list = getKeys(data);
var len = key_list.length, i, index, temp, _index, result, key;
for (i = 0; i < len - 1; i++) {
//随机下标
index = ~~(Math.random() * (len - i));
//临时缓存数据
temp = key_list[index];
//交换位置
_index = len - 1 - i;
key_list[index] = key_list[_index];
key_list[_index] = temp;
}
for (i = 0; i < len; i++) {
key = key_list[i];
if (type === "[object Array]") {
result || (result = []);
opt ? result[key] = data[key] : result.push(data[key]);
} else if (type === "[object Object]") {
result || (result = {});
opt ? result[key] = data[key] : result[i] = data[key];
} else {
result || (result = []);
opt ? result[key] = data[key] : result.push(data[key]);
}
}
reg_str.test(type) && (result = result.join(""));
return result;
}
如图: