1、自定义Array.prototype.unshift
(1)利用splice,改变原数组
Array.prototype.unshift = function(){for(var position = 0;position < arguments.length; position++){this.splice(position, 0, arguments[position])}return this.length}
(2)利用concat,不改变原数组,返回新数组。利用Array.prototype.slice.call(arguments)将类数组转换成数组
Array.prototype.myUnshift = function(){for(var i = 0; i < arguments.length; i++){//this = [arguments[i]].concat(this) => 函数运行期间不能给this赋值,否则会报错。}}Array.prototype.myUnshift = function(){let arr = Array.prototype.slice.call(arguments);//当有多个参数时并包含concat时,参数数组会被‘扁平化’,//这个是concat的特性导致(参数为数组时,合并数组,为其他值时,将参数push到数组末尾)let newArr = this.concat(arr)return newArr}
2、根据每个元素的总字节数,对数组进行排序
function sumStrBytes(str){let sumBytes = str.lengthfor(var i = 0; i <str.length; i++){if(str[i].charCodeAt() > 255) sumBytes++}return sumBytes}function sortByStrBytes(arr){arr.sort((a,b)=>{return sumStrBytes(a) - sumStrBytes(b)})}
3、封装更精确的typeof方法
//先判断是否为null//再根据typeof返回结果来区别引用值和原始值function myTypeof(val){var toString = Object.prototype.toString,resOfToString = toString.call(val),resOfTypeof = typeof(val),exactTypeMatch = {'[object Objec]' : 'object','[object Function]' : 'function','[object Array]' : 'array','[object Number]' : 'object number','[object String]' : 'object string','[object Boolean]' : 'object boolean'}if(val === null){return 'null'}else if(resOfTypeof === 'object'){return exactTypeMatch[resOfToString]}else{return resOfTypeof}}
4、数组去重
利用对象属性名唯一的特点
Array.prototype.unnique = function(arr){let temArr = [],obj = {};for(var i = 0; i < this.length; i++){if(!this[i]){obj[this[i]] = true //赋一个正值,给之后判断留一个标记,//非得直接将元素作为属性名的话,可以用hasOwnProperty来判断,是否已经赋值了temArr.push(obj[this[i]])}}return temArr}//用forEach和Object.values方法Array.prototype.unique = function(arr){let obj = {};this.forEach((item)=>{if(!obj[item]){obj[item] = item}})console.log(Object.values(obj))return Object.values(obj)}
5、找出字符串中第一个只出现一次的字符
思路,循环字符串,给每个字符记录出现次数。记录后,循环记录对象,找出第一个属性值为1的属性。
let str = 'eqwerqwerqewrrasdfej';function recordStrAmount(arr){let obj = {};for(var i = 0; i<arr.length; i++){if(obj.hasOwnProperty(arr[i])){obj[arr[i]]++}else{obj[arr[i]] = 1}}//得到字符出现次数for(var key in obj){if(obj[key] === 1){return key}}}
6、一些面试题
(1)函数表达式与typeof
let fn = funciont myFn(){}console.log(typeof(myFn)) // 返回undefined,typeof(undefined 和 为定义的变量)//myFn()报错,因为函数表达式会忽略函数名,//在外部是访问不到该函数的,但是在函数内部可以自调用
(2)利用逗号制造稀松数组来适应取值
let arr=['一','二','三'];//参数传阿拉伯数字,打印对应大写汉字//如果不将传入的数字减一,可以操作数组arr=[,'一','二','三']
