饿了么二面是在线写代码,有三道题,一道题十分钟内写完提交,在一个网站写,会自动录制代码编写过程
首先写了一个判断数组的函数
123function isArray(array) {return !!array && Object.prototype.toString.call(array) === "[object Array]";}有序数组的打乱
1234567function random(array) {if(!isArray(array)) return array;return array.sort(function() {return 0.8 - Math.random();});}多维数组变为一维数组
1234567891011121314151617181920212223242526272829303132function flatten(array) {if(!isArray(array)) return [array];let len = array.length;let flattenArr = [];for(let idx=0;idx<len;idx++) {Array.prototype.push.apply(flattenArr, isArray(array[idx]) ? flatten(array[idx]) : [array[idx]]);}return flattenArr;}// 使用 ES6 的 Generator 函数实现function flattenES6(array) {function* iterator(array) {if(isArray(array)) {for(let i=0;i<array.length;i++) {yield* iterator(array[i]);}}else {yield array;}}let result = [];for(let value of iterator(array)) {result.push(value);}return result;}将一个乱序数组,里面有
*
和数字
,将*
提到最前,数字往后放,并且数字顺序不变123456789101112131415161718192021222324252627function arrange(array) {if(!isArray(array)) return array;let prePoint = 0,nextPoint = 1,len = array.length;while(true) {while(array[prePoint] === "*" && prePoint < len) {prePoint++;}while(array[nextPoint] !== "*" && nextPoint < len) {nextPoint++;}while(prePoint > nextPoint) {nextPoint++;}if(prePoint >= len || nextPoint >= len) {break;}// exchange[array[prePoint], array[nextPoint]] = [array[nextPoint], array[prePoint]];}return array;}