Fe-interview: [js] 第339天 写个方法近似计算指定数组或对象占用内存的大小

Created on 19 Mar 2020  ·  1Comment  ·  Source: haizlin/fe-interview

第339天 写个方法近似计算指定数组或对象占用内存的大小

我也要出题

js

Most helpful comment

js function sizeOfObject(obj)){ if(object == null){ return 0 } var bytes = 0 for (var key in obj) { if (!Object.hasOwnProperty.call(obj, key)) { continue } bytes += sizeof(key) try { bytes += sizeof(obj[key]) } catch (ex) { if (ex instanceof RangeError) { bytes = 0 } } } return bytes } function sizeOf(obj){ var objType = typeof obj switch(objType){ case 'string': return obj.length*3; case 'boolean' return 1; case 'number': return 8; case 'object': if(Array.isArray(obj)){ return obj.map(sizeOf).reduce(acc,curr)=>acc+curr,0) }else{ return sizeOfObject(obj) } default: return 0 } }

>All comments

js function sizeOfObject(obj)){ if(object == null){ return 0 } var bytes = 0 for (var key in obj) { if (!Object.hasOwnProperty.call(obj, key)) { continue } bytes += sizeof(key) try { bytes += sizeof(obj[key]) } catch (ex) { if (ex instanceof RangeError) { bytes = 0 } } } return bytes } function sizeOf(obj){ var objType = typeof obj switch(objType){ case 'string': return obj.length*3; case 'boolean' return 1; case 'number': return 8; case 'object': if(Array.isArray(obj)){ return obj.map(sizeOf).reduce(acc,curr)=>acc+curr,0) }else{ return sizeOfObject(obj) } default: return 0 } }

Was this page helpful?
0 / 5 - 0 ratings