面试题(一)
try{ var data1 = [4,5,6,7,8,9,10,11,12]; var data2 = { "a": 4, "b": 5, "c": 6 }; console.group(data1); each(data1, function(o){ if( 6 == this ) return true; else if( 8 == this ) return false; console.log(o + ": \"" + this + "\""); }); console.groupEnd(); /*------[执行结果]------ 1: "4" 2: "5" 4: "7" ------------------*/ console.group(data2); each(data2, function(v, n){ if( 5 == this ) return true; console.log(n + ": \"" + v + "\""); }); console.groupEnd(); /*------[执行结果]------ a: "4" c: "6" ------------------*/ }catch(e){ console.error("执行出错,错误信息: " + e); }
一、先明确data1、data2 明显是两种类型,1是数组,2是json格式。
二、要了解原生js里面并没有each方法,明显本题目是想让我们根据不同的参数类型,执行不一样的each方法。
三、输出时console的事情,无需过问。
var each = function(o,fn){ if(o instanceof Array){ //Array 类型 for(var i=0;i<o.length;i++){ if(fn.call(o[i])==false){ i = o.length //false时候结束 } } } else{ for(proName in o) fn.call(o[proName],proName) } }