10 09/2014

javascript quiz 3

最后更新: Wed Sep 10 2014 12:37:50 GMT+0800

继续算题吧(点击代码,看结果)

var x="5", y=10; 
alert(+x+y);

(function() {
kittySays = "Meow";
})();
alert(kittySays);

(function() {
var kittySays = "Meow";
})();
alert(kittySays);

function foo() {
kittySays = "Meow";
})();
alert(kittySays);

var x = 15, y = 10;
alert(x+++y);

var x = 15, y = 10;
alert(x++-++y);
  • x++ 先返回 x,然后 +1;
  • ++y 先+1,然后返回 y

This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for example, x—), then it returns the value before decrementing. If used prefix (for example, —x), then it returns the value after decrementing. ——mdn


var x = 15, y = 10;
alert(x++-++y+x++);

15 - 11 + 16


alert('99' < '101')

比字母顺序呢!(Strings are compared based on standard lexicographical ordering, using Unicode values.)


var x = "99", y="101";
alert (x<+y);

字符串和数字比较,都先转成数字,然后再比

When Type conversion is involved in the comparison (i.e. non–strict comparison), JavaScript converts Type String, Number, Boolean, or Object operands as follows:

  • When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
  • If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
  • If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.
  • Note that an object is converted into a primitive if, and only if, its comparand is a primitive. If both operands are objects, they’re compared as objects, and the equality test is true only if both refer the same object.
    via MDN

alert(typeof typeof(undefined));

typeof(undefined) 得到 “undefined”,而 “undefined” 是字符串


alert(foo());
var foo = function () { return "zz";};

var 优先,所以等于

var foo;

alert(foo());

foo = function () { return “zz”;};


alert (foo());
function foo() { return "zz";}

var foo = function bar() { }; 
alert(typeof bar);

来自 http://net.tutsplus.com/articles/quizzes/nettuts-quiz-3-javascript/