2013-05-13 54 views
1

我试图让浏览器窗口宽度的结果,并试图把数学和条件的结果变量,这是代码返回通过存储在一个变量

var MyWidth = 1900; 
var MyHeight = 900; 
var height = $(window).height(); 
var width = $(window).width(); 

var AutoW = function() { 
    if ((MyWidth/width).toFixed(2) > 0.95) 
      return 1; 
    if ((MyWidth/width).toFixed(2) < 1.05) 
      return 1; 
    else return (MyWidth/width).toFixed(2); 
    }; 


alert(AutoW); 
函数运算结果的值

问题是我不知道赋给变量

什么是代码的正确方法函数的正确的语法或结构?

+0

AutoW只是在运行时定义的函数,尝试调用alert(AutoW()),您将获得价值。现在如果你想获得这个函数的值AutoW,然后声明另一个函数,并调用它与赋值 – Kasma 2013-05-13 07:03:34

回答

2

alert(AutoW());

AutoW()返回分配给该变量的函数的值。

小提琴:http://jsfiddle.net/V2esf/

+0

哦,我没有注意到,或更好地说,不知道规则..认为代码本身有问题 – LoneXcoder 2013-05-13 07:05:36

1
var AutoW = function() { 
    // don't calculate ratio 3 times! Calculate it once 
    var ratio = (MyWidth/width).toFixed(2); 
    if (ratio > 0.95) 
      return 1; 
    if (ratio < 1.05) 
      return 1; 
    else return ratio; 
}; 


// alert(AutoW); - this was a problem, AutoW is a function, not a variable 
// so, you should call it 
alert(AutoW()); 
+0

当然,我想到的问题(:,但谢谢你的完整答案(我仍然处在第一阶段的想法是什么时候有这个'问题') – LoneXcoder 2013-05-13 07:11:36

1
<script> 
    var MyWidth = 1900; 
    var MyHeight = 900; 
    var height = $(window).height(); 
    var width = $(window).width(); 

    var AutoW = function() { 
     if ((MyWidth/width).toFixed(2) > 0.95) 
      return 1; 
     if ((MyWidth/width).toFixed(2) < 1.05) 
      return 1; 
     else return (MyWidth/width).toFixed(2); 
    }; 

    var val = AutoW(); 
    alert(val) 
</script> 
1

你应该试试这种方法:

(function(){ 

var MyWidth = 1900, 
MyHeight = 900, 
height = $(window).height(), 
width = $(window).width(), 
result; 

var AutoW = function() { 
    var rel = (MyWidth/width).toFixed(2); 
    return ((rel > 0.95) && (rel < 1.05)) ? 1 : rel; 
}; 

result = AutoW(); 

alert(result); 

})(); 

但要记住你写始终返回1的功能,这就是为什么我改变它(& & )的条件,使其成为一个过滤器。

如果您提醒功能,您将返回整个功能。你必须将一个函数“()”的转换赋值给一个变量,这样返回值将被赋值给它。

var result = f_name(); 

请记住,尽量不要使用全局变量,将所有内容包装在一个函数中。

你应该把if后面的{}和缓存值用作多次,比如当我将“MyWidth/width).toFixed(2)”缓存到rel时。

我用sintax而不是如果>>(条件)? (如果匹配则返回):(return else);

+0

不错的一个,你能提醒我的名字“condition?return:return else “? – LoneXcoder 2013-05-13 07:43:03

+0

三元运算符和短条件:) http://msdn.microsoft.com/en-us/library/ie/be21c7hw%28v=vs.94%29.aspx – 2013-05-13 09:32:13