新人求助2个js问题


1. return "hello"+(who?","+who:"");
这行代码是判断who是否为空吗?没见过这个语法

2.
var type="" function Block(){ this.new=function(){ type=type||"B1"; } this.transform=function(type){ switch(type){ case "B1"://变纵向 type="B2"; break; case "B2"://变横向 type="B1"; break; } } } var b=new Block(); var c=b.new(); var a=b.transform(type); alert(type); b.transform(type); alert(type);
为什么b.transform(type)不能把全局变量中的B1改为B2

这插入代码片段为什么没有格式...

javascript属性类型 JavaScript

@非常喜欢 10 years, 10 months ago

1.麻烦去搜索一个三元运算符

2.就是闭包。


 var type="";
        function Block()
        { 

            this.new=function()
            {
                type=type||"B1"; 
            } 

            this.transform=function(type)
            {
                switch(type)
                { 
                    case "B1":
                    //变纵向 
                    type = "B2";
                    break; 
                    case "B2":
                    //变横向 
                    type="B1"; 
                    break; 
                }
                function returnFun()
                {
                    return type;
                }

                return returnFun;

            } 
        } 

        var b=new Block();
        var c=b.new();
        var a=b.transform(type);
        alert(a());
        b.transform(type); 
        alert(type);

海猫络合物 answered 10 years, 10 months ago

也可以这样理解吧:return "hello" + (who || '');

米米羊的翅膀 answered 10 years, 10 months ago

1.是的,括号里面的是一个三元表达式。
2. js 调用方法传参是值传递,即 b.transform(type) 实际传进去的是 type 的值 "B1" ,在 transform() 方法内部的 type 变量的值才会改变。如果楼主想达到改变全局 type 的值的效果,可以将 transform 方法的定义改为无参数。

slikine answered 10 years, 10 months ago

直接贴代码吧,希望能看懂。希望以后发问题时代码能够整理下吧

1.


 var a = who ? who : '';
return "hello"+a;

2.


 var type="" ;
function Block(){ 
    this.new = function(){ 
        type = type || "B1"; 
    };
    this.transform = function(arg){ 
        switch(arg){ 
            case "B1"://变纵向 
            arg= "B2"; 
            break; 
            case "B2"://变横向 
            arg= "B1"; 
            break; 
        } 
      type = arg;
    };
} 
var b = new Block(); 
var c = b.new(); 
var a = b.transform(type); 
console.log(type); 
b.transform(type); 
console.log(type);

暴力大哥大 answered 10 years, 10 months ago

Your Answer