美文网首页
Javascript 练习

Javascript 练习

作者: peerben | 来源:发表于2016-11-07 21:29 被阅读43次

    在Array()构造器以及相关的数组文本标识法都不存在的情况下,自定义一个类似的MyArray()构造器,并令其通过以下测试:

    var a = new MyArray(1,2,3,"test");
    a.toString();
    //"1,2,3,test"
    
    a.length;
    //4
    
    a[a.length-1];
    //"test"
    
    a.push("boo");
    //5
    
    a.toString();
    //"1,2,3,test,boo"
    
    a.pop();
    //boo
    
    a.toString();
    //"1,2,3,test"
    
    a.join(",");
    //"1,2,3,test"
    
    a.join(" isn\'t");
    //1 isn't 2 isn't 3 isn't test"
    
    function MyArray() {
        this.length = arguments.length;
    
        for (var i=0; i<this.length; i++){
            this[i] = arguments[i];
        }
    
        this.toString = function () {
            var string = "";
            for (var i=0; i<this.length; i++){
                string += string ? (", "+this[i]) : this[i];
            }
            return string;
        };
    
        this.push = function (elem) {
            this[this.length] = elem;
            this.length++;
        };
    
        this.pop = function () {
            return this[--this.length];
        };
    
        this.join = function (sep) {
            var string = "";
            for(var i=0; i<this.length; i++){
                string += this[i] + ((i==this.length-1) ? "": sep);
            }
            return string;
        };
    }
    
    var a = new MyArray(1, 2, 3, "test");
    
    console.log(a.toString());
    console.log(a.length);
    console.log(a[a.length-1]);
    a.push("boo");
    console.log(a.toString());
    a.pop();
    console.log(a.toString());
    console.log(a.join(","));
    console.log(a.join(" isn\'t "));
    

    相关文章

      网友评论

          本文标题:Javascript 练习

          本文链接:https://www.haomeiwen.com/subject/ogoouttx.html