JavaScript中的强制

We are going to talk about Coercion in JavaScript, it is a mouthful word but still, a lot of people do not know about it even a coercion. So what is coercion in the context of JS, my answer to will be, Sometimes the JavaScript wants to the smartest guy in the room, sometimes it is and sometimes it is not? JavaScript tries to predict and do something for you, sometimes it does it perfectly and sometimes is not able to do it so perfectly so we need to be aware where Javascript can make a mess and where can do predictions (by prediction we don't mean Machine learning or AI). JavaScript tries to become smart and try to do something for us but we don't want it to do. So it is better to understand how JavaScript will predict these things to our advantage.

我们将要讨论JavaScript中的Coercion ,这是一个令人难以置信的词,但很多人甚至都不知道它是强制性的 。 那么,在JS上下文中什么是强制性的?我的回答是:有时候JavaScript想要房间里最聪明的人,有时候是,有时候不是? JavaScript会尝试为您预测并为您做某事,有时它做得很完美,有时却做不到那么完美,因此我们需要知道Javascript在哪里会弄得一团糟,在哪里可以做预测(通过预测,我们并不是说机器学习或AI)。 JavaScript试图变得聪明,并尝试为我们做些事情,但我们不希望它做。 因此,最好了解JavaScript将如何预测这些事情以使我们受益。

Case 1:

情况1:

Let’s look some examples...

让我们看一些例子...

Example 1:

范例1:

console.log('5' - 5);

Output

输出量

coercion in JS - Output 1

So it seems that JavaScript interpret '5' as an integer instead of a string. It producesan output of 0. Well, this is helpful (thank you JavaScript).

因此,似乎JavaScript将“ 5”解释为整数而不是字符串。 输出为0。这很有用(感谢JavaScript)。

Example 2:

范例2:

console.log('5' + 5);

From example 1 we can guess its output to be 6, right? Well, no..!

从示例1中,我们可以猜测其输出为6,对吧? 好吧,不!

Output

输出量

coercion in JS - Output 2

The output is 55 which is not clearly 6 so what happened here? JavaScript took 5 as a string and concatenate it as 55.

输出为55,这显然不是6,那么这里发生了什么? JavaScript将5作为字符串,并将其连接为55。

As a proof have a look on next code snippet [code snippet 1]:

作为证明,请查看下一个代码段[ 代码段1 ]:

console.log(typeof('5' - 5));
console.log(typeof('5' + 5))

Output

输出量

coercion in JS - Output 3

typeof: This typeof function returns the type of the entity passed as a parameter.

typeof :此typeof函数返回作为参数传递的实体的类型。

Now, this is coercion, In JavaScript, we have three types of coercion, with:

现在,这是强制性的。在JavaScript中,我们有三种类型的强制性,分别是:

  1. numbers

    数字

  2. strings

  3. Boolean

    布尔型

Case 2:

情况2:

So the whole idea is you should never allow JavaScript to predict for you if you want to result in numbers be sure it is an integer or float, and if you want string then make sure it is string properly, otherwise these things will generate errors which are basically logical error and can not be identified by JS.

因此,整个想法是,如果要生成数字,则绝对不要让JavaScript为您预测,以确保它是整数或浮点数;如果要使用字符串,则请确保它正确地是字符串,否则这些事情将产生错误,基本上是逻辑错误,JS无法识别。

Now there is one thing in coercion, let’s see another example [example 3]:

现在强制中有一件事,让我们看另一个示例[示例3]:

const add = true + 10
console.log(add);

If I make a constant variable add where I add '10' with 'true' (I know it is strange, let’s say it is some use case scenario),

如果我做一个常数变量添加在那里我加“10”与“真”(我知道这是奇怪的,让我们说这是一些使用情况),

Output

输出量

coercion in JS - Output 4

Now the output is '11', JavaScript treated truly as a literal one, which is true of course. Now for false, let's see an example [example 4]:

现在的输出为'11' ,JavaScript确实被视为一个字面值,这当然是正确的。 现在为false ,让我们看一个示例[示例4]:

const add = false + 10
console.log(add);

Output

输出量

coercion in JS - Output 5

Now it is obvious that false have 'zero' literal value.

现在很明显,false具有“零”字面值。

In JavaScript 'true' is treated as one and 'false' as zero.

在JavaScript中, “ true”被视为1, “ false”被视为零。

Case 3:

情况3:

Now I will explain more of coercion using a use case scenario:

现在,我将使用用例场景来说明更多强制性:

[code snippet 2]:

[代码段2]:

const loginDetails = []     //line 1
const loginID =loginDetails[0]     //line 2

if(loginID !== undefined) {        //line 3
	console.log('Allow user Login');
}else{      //line 4
	console.log('Auth failed');
}

Let's say we want a user's login credentials from a database and stored it in loginDeatails which we usually receive in an array format (that is in line 1). Normally we get Login details at first position (or just assume) so we stored it in loginID on line 2. To check whether we successfully we checked if loginID is whether undefined or not (line 3). Can you predict its output?

假设我们要从数据库中获取用户的登录凭据,并将其存储在通常以数组格式(即第1行)中接收到的loginDeatails中。 通常,我们在第一个位置(或只​​是假设)获得登录详细信息,因此我们将其存储在第2行的loginID中。要检查是否成功,我们检查了loginID是否为未定义 (第3行)。 你能预测它的输出吗?

Output

输出量

coercion in JS - Output 6

It is obvious as we don’t have any data inside loginID.

很明显,因为我们在loginID中没有任何数据。

[code snippet 3]:

[代码段3]:

const loginDetails = []
const loginID =loginDetails[0]

if(loginID) {        //line 1
	console.log('Allow user Login');
}else{
	console.log('Auth failed');
}

Code snippet 3 is similar to code snippet 2 just with a difference in line 1 of code snippet 3 (the same line is line 3 in snippet 2). Now again if we run we will get an "Auth failed" output so loginID is treated as false (because it was undefined).

代码段3代码段2相似,只是代码段3的第1行不同(同一行是代码段2中的第3行)。 现在,如果再次运行,将获得“验证失败”的输出,因此将loginID视为false (因为未定义)。

Now, what are the things which JavaScript take it as false? Well, they are:

现在,JavaScript将其视为错误的是什么? 好吧,它们是:

  1. false

  2. 0 (zero)

    0 (零)

  3. '' (empty string without spaces, else even a single space or any token inside it will be true)

    '' (没有空格的空字符串,否则即使是单个空格或其中的任何标记都将为true)

  4. null

    空值

  5. undefined

    未定义

Apart from these everything else is true.

除了这些, 其他一切都是正确的

That’s all in Coercion which is a bit tricky.

这一切都在Coercion中 ,这有点棘手。

翻译自: https://www.includehelp.com/code-snippets/coercion-in-javascript.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值