最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Could you explain these two javascript examples? - Stack Overflow

programmeradmin0浏览0评论

1: Why is the result of foo && baz not 1? Because true is 1.

var foo = 1;
var baz = 2;

foo && baz;   // returns 2, which is true

2: There are two pluses in the console.log(foo + +bar);, what's the meaning of them?

var foo = 1;
var bar = '2';
console.log(foo + +bar);

1: Why is the result of foo && baz not 1? Because true is 1.

var foo = 1;
var baz = 2;

foo && baz;   // returns 2, which is true

2: There are two pluses in the console.log(foo + +bar);, what's the meaning of them?

var foo = 1;
var bar = '2';
console.log(foo + +bar);
Share Improve this question edited Jun 24, 2011 at 12:00 Lombo 12.2k2 gold badges23 silver badges28 bronze badges asked Jun 24, 2011 at 11:53 runeverydayruneveryday 2,7994 gold badges32 silver badges44 bronze badges 2
  • These are two very separate questions, probably should be separated. – Orbling Commented Jun 24, 2011 at 11:55
  • 5 This is javascript not jQuery. – Jazaret Commented Jun 24, 2011 at 11:55
Add a ment  | 

3 Answers 3

Reset to default 10

That's because the && (logical AND) operator returns the value of the last operand it evaluated. Since foo is true, it has to evaluate bar to determine the oute of the expression (it will only be true if bar is also true).

The opposite would happen with the || (logical OR) operator. In that case, since foo is true, the oute of the expression is known to be true without having to evaluate bar, so the value of foo will be returned.

Concerning your second question, the unary + operator allows to convert the string '2' into the number 2.

&& returns the value of the last evaluated value. ´&&´ is a operator. Most of the time it used in a context like this

if ( something && somethingelse ) {}

in other words

0 && 2 //would return 0 because 0 is a falsy value
12 && 10 && 0 && 100 // would return 0 to 
10 && 123 && "abc" // returns "abc"

+ is a mathematical operator but it can be used to convert a string in to a number.

1 + 1 = 2
1 + '1' = 11 //van damme would like this one
1 + +'1' = 2 // somce '1' got converted to a number

Javascript follows Short Circuit Evaluation. So according to this, javascript returns the last value if both the values are true

发布评论

评论列表(0)

  1. 暂无评论