先前我写了一篇PHP的常用函数库function.php,里面有俩个函数 getItemId 和 getRandNumber ,今天就看看用Js改写之后是怎样的:
/** * 生成itemId * @return string */ function getItemId() { var myDate = new Date(); var hour = (Math.ceil((myDate - new Date(myDate.getFullYear().toString())) / (24 * 60 * 60 * 1000)) + 1) * 24 + myDate.getHours(); var num = 4 - hour.length; var str = ''; if (num > 0) { for (var i = 0; i < num; i++) { str += '0'; } } str += hour; var start = myDate.getFullYear().toFixed().slice(-2); return start + str + getRandNumber(10); } /** * 生成固定长度的随机数 * * @param int $length * @return string */ function getRandNumber(number) { var str = "", arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; for (var i = 0; i < number; i++) { pos = Math.round(Math.random() * (arr.length - 1)); str += arr[pos]; } return str; } console.log(getItemId()); console.log(getRandNumber(6));
没有难的技术,当你弄清它的原理时,你会发现原来如此简单~ 欢迎加群【536501561】讨论