JavaScript的类型转换:(真放;&安培; 1)VS(真| | 1) [英] JavaScript type conversion: (true && 1) vs (true | | 1)

查看:122
本文介绍了JavaScript的类型转换:(真放;&安培; 1)VS(真| | 1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript是不严格的类型语言如Java,例如。

据我们所知,它依赖于上下文转换的结果值:

2+3结果23

2*3结果 6

这是理解相当明确和确定。

我只是尝试以下EX pressions和糊涂了:

真放;&安培; 1 结果 1 结果
真|| 1 结果真正

为什么第一次给了号,第二个给了布尔?

考虑到JavaScript的转换规则,我希望得到在这两种情况下布尔值,由于布尔前的背景下pression。


解决方案

Crockford的网站,它说:


  

&将功放;&安培;运营商通常称为逻辑和。它也可以被称为
  守卫。如果第一个操作数是假的,空,不确定的,(空
  字符串),或数字0,则返回第一个操作数。除此以外,
  它返回第二个操作数。这提供了编写一个方便的方法
  一个空检查:


  VAR值= P&放大器;&安培; p.name; / * name的值将只能从检索
p如果p的值,从而避免错误。 * /


  

该||运营商通常是
  称为逻辑或。它也可以被称为默认。如果第一操作数
  是假的,空,不确定的,(空字符串),或数字0,
  然后返回第二个操作数。否则,它返回第一
  操作数。这提供了指定默认值的便捷方式:


 值= V || 10; / *使用的v的值,但是当v不具有值,
用10来代替。 * /

JavaScript is non-strictly typed language as Java,for example.

As we know, it converts value of result dependently upon context:

"2" + "3" results "23"

"2" * "3" results 6

This is quite clear and OK for understanding.

I just tried following expressions and got confused:

true && 1 results 1
true || 1 results true

Why the first gives Number and the second gives boolean?

Considering JavaScript conversion rules,I expect to get boolean values in both cases,due to boolean context of expression.

解决方案

Check Douglas Crockford's site, it says:

The && operator is commonly called logical and. It can also be called guard. If the first operand is false, null, undefined, "" (the empty string), or the number 0 then it returns the first operand. Otherwise, it returns the second operand. This provides a convenient way to write a null-check:

var value = p && p.name; /* The name value will only be retrieved from
p if p has a value, avoiding an error. */

The || operator is commonly called logical or. It can also be called default. If the first operand is false, null, undefined, "" (the empty string), or the number 0, then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values:

value = v || 10; /* Use the value of v, but if v doesn't have a value,
use 10 instead. */

这篇关于JavaScript的类型转换:(真放;&安培; 1)VS(真| | 1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆