传说中的2011搜狐JavaScript面试题(一)

要求:
1、只能在指定的位置填写自己的代码,本文件里的其他代码不能修改
2、所有题目都不允许添加全局变量名
3、本文件应该能在firebug的console里正常执行,并输出结果
4、代码最优化,效率最高
5、代码注释明确

练习1:
实现一个遍历数组或对象里所有成员的迭代器。

 

js Code
var each = function(obj, fn){
        //+++++++++++答题区域+++++++++++
        



        //+++++++++++答题结束+++++++++++
};

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);
}

答案

Answer Code
var each = function(obj, fn){
        //+++++++++++答题区域+++++++++++
        if(obj instanceof Array || typeof obj.length === 'number'){
         for (var i = 0, len = obj.length; i < len; i++) {
                        if (fn.call(obj[i], i + 1) === false)
                                break;
                }
        }else{
            for(o in obj){
                fn.call(obj[o],obj[o],o) ;
            }
        }
        //+++++++++++答题结束+++++++++++
};


来自:W3CFUNS

 

学习到知识:

1.Function.call()

将函数作为对象的方法调用

摘要

function.call(thisobj, args...)

参考

thisobj
    调用function的对象。在函数主体中,thisobj是关键字this的值。如果这个参数为null,就使用全局对象。
args
    任意多个参数,这些参数将传递给函数function。

返回值

调用函数function的返回值。

抛出

TypeError
    如果调用该函数的对象不是函数,则抛出该异常。

常量

 

描述

call()将指定的函数function将对象thisobj的方法来调用,把参数列表中thisobj后的参数传递给它,返回值是调用函数后的返回值。在函数体内,关键定this引用thisobj对象,或者如果thisobj为null,就使用全局对象。

如果指定数组中传递给函数的参数,请使用Function.apply()方法。

例子

    // Call the default Object.toString( ) method on an object that
    // overrides it with its own version of the method. Note no arguments.
    Object.prototype.toString.call(o);

API文档来自:qefqei

 

2.instanceof 

变量 instanceof 类型

判断指定对象是否所属类型,返回false,true.

例如:

var obj =  [];

obj instanceof Array返回ture.

3.typeof

typeof 变量 === '类型字符串'

例如:

typeof obj.length === 'number'

 

 

posted @ 2012-06-28 13:32  时生  阅读(333)  评论(0编辑  收藏  举报