javascript最大值_JavaScript的非值三重奏

news/2024/7/24 2:26:47 标签: python, javascript

javascript最大值

Undefined, Null, and NaN are 3 keywords, known as non-values or empty values, that are often a source of buggy code, stress, and confusion for many beginning JavaScript engineers. Part of the reason for that is that they are seldom given the proper attention they merit in most courses or books, in my humble opinion. Here, we will attempt to give this trio its proper due and uncover its mysteries.

Undefined,Null和NaN是3个关键字,称为非值或空值,对于许多新手JavaScript工程师而言,它们通常是错误代码,压力和混乱的根源。 造成这种情况的部分原因是,根据我的拙见,很少在大多数课程或书籍中给予他们应有的重视。 在这里,我们将尝试给予此三人适当的应得的费用,并揭示其奥秘。

未定义 (Undefined)

This keyword is both a data type and value in JavaScript. It is one of six primitive data types, the others being: string, number, boolean, null, and symbol (ES5+). It is assigned, by default, to any variable whose value has not yet been defined. On a deeper level, this means that the variable exists but its value has been given an empty value, called undefined. JavaScript is a dynamically typed language, which means that the JS engine determines the type of a variable based on the data type of the value assigned to it. In that context,undefined really means that JavaScript doesn’t know about type of the variable declared because it has yet to be initialized with a value.

此关键字在JavaScript中既是数据类型又是值。 它是六种原始数据类型之一,其他为: stringnumberbooleannullsymbol (ES5 +)。 默认情况下 ,将其分配给尚未定义其值的任何变量。 从更深层次上讲,这意味着该变量存在,但其值已被赋予一个空值,称为undefined 。 JavaScript是一种动态类型化的语言,这意味着JS引擎根据分配给它的值的数据类型来确定变量的类型。 在这种情况下, undefined实际上意味着JavaScript不知道声明的变量的类型,因为尚未使用value对其进行初始化

Any unassigned variable is automatically given the value and type of undefined

任何未分配的变量都会自动获得undefined的值和类型

We can illustrate this with the code below.

我们可以使用下面的代码来说明这一点。

let myVar;  //declared but left unassigned
console.log(myVar)

Output: undefined

输出: undefined

Undefined is also a data type, hence the following:

Undefined也是数据类型,因此如下所示:

console.log(typeof myVar)

Output: "undefined"

输出: "undefined"

Notice that there’s a slight difference between the value and the type of undefined; the latter is in quotes. One of the questions that you may find on an interview question is:

注意, undefined的值和类型之间存在细微的差别; 后者用引号引起来。 在面试问题上可能会发现的问题之一是:

What is the value of typeof typeof undefined?

typeof typeof undefined 的值是什么

The answer is: string

答案是: string

This means that we can type the following:

这意味着我们可以输入以下内容:

console.log(typeof myvar + “ variable”)

console.log(typeof myvar + “ variable”)

Output: undefined variable

输出: undefined variable

We can therefore say that in JavaScript, the data type of the data type of undefined is string!

因此,可以说在JavaScript中, undefined 数据类型的数据类型 string

For functions, if the returned value is left unassigned, it returns undefined. More importantly, a function will also return undefined if a value was not returned.

对于函数,如果未分配返回值,则返回undefined 。 更重要的是,如果未返回值,则函数也将返回undefined

function f(){
return;
}console.log(f())

Output: undefined

输出: undefined

空值 (Null)

Null is also a primitive data type in JavaScript, that can also be assigned as a value. However, unlikeundefined, its data type is Object.

Null也是JavaScript中的原始数据类型,也可以将其分配为值。 但是,与undefined不同,其数据类型为Object

let myVar = null;
console.log(myVar)

Output: null

输出: null

Console.log(typeof myVar);

Output: Object

输出: Object

Null is used to intentionally give an empty value to something. It’s common practice to have functions return null when a condition is not met. For instance, JavaScript’s built-in match() function returns the object that match a pattern for a given string and null otherwise.

Null用于有意将某物赋予空值。 通常的做法是在不满足条件时使函数返回null。 例如,JavaScript的内置match()函数返回与给定字符串的模式匹配的object ,否则返回null

console.log( "Abe".match(/[aeiou]/gi). )

Output: [ ‘A’, ‘e’ ]

输出: [ 'A', 'e' ]

console.log( "PS4".match(/[aeiou]/gi). )

Output: null

输出: null

Therefore, null is the intentional absence of an expected object value. It’s important to understand that null is used in conjunction with objects. The return value of match() is an array (an object) if a match is found and null otherwise.

因此,null是故意缺少预期的对象值。 重要的是要了解将null与对象结合使用。 如果找到匹配项,则match()的返回值是一个数组(对象),否则返回null

The key difference between undefined and null is that:

undefinednull之间的主要区别在于:

  • undefined means that the variable is known, but its value isn’t, hence its data type is unknown

    undefined表示变量是已知的,但其值未知,因此其数据类型未知

  • null means that the data type of the variable is known (Object), but its value is deliberately left unknown (empty) because no object is relevant for a given condition.

    null表示变量的数据类型是已知的( Object ),但是故意将其值保留为未知(空),因为没有对象与给定条件相关。

  • undefined is automatically assigned, if the value is unknown

    如果值未知,则将自动分配undefined

  • null is deliberately assigned, when no object is relevant

    如果没有对象相关,则故意分配null

Null represents nothingness or absence and can be thought of as being equivalent to 0. As a matter of fact, in some languages like C++ and Java, it is.

Null表示什么都不 存在不存在 ,可以被认为等于0。事实上,在某些语言(如C ++和Java)中,它是。

Let look at a few quirks related to null and undefined.

让我们看一些与nullundefined相关的怪癖。

null === undefined   // false
null == undefined // true

The first statement checks to see if the value on the left is exactly like the one on the right. That’s what the ‘threequals’ (===) operator does. For double-equals, because JavaScript is dynamically typed, when it sees a value it attempts to figure out its data type. If the two values are not of the same type, it will convert or coerce (or cast) one of them to the data type of the other, before making the comparison. For example, if a string and a number are compared, JavaScript will cast the former to the latter. That’s why 0 == ‘0’ and ‘0’ == false are true. ‘0’ is cast to type number and then compared, which returns true. Similarly, due to type coercion, null is doubly equal to undefined. Keep in mind that this is a quirk that is particular to JavaScript; in most languages, such a confusing concept doesn’t exist.

第一条语句检查左侧的值是否与右侧的值完全相同 。 这就是“ 三个质量”(===)运算符的作用。 对于双等号,因为JavaScript是动态类型的,所以当看到值时,它将尝试找出其数据类型。 如果这两个值是相同类型的不是,它会转换或强迫 (或CAST)其他的数据类型其中之一,在进行比较之前 。 例如,如果将stringnumber进行比较,JavaScript会将前者转换为后者。 这就是为什么0 == '0''0' == false为true。 ' 0 '被强制转换为number类型,然后进行比较,然后返回true。 类似地,由于强制类型, null双重等于undefined 。 请记住,这是JavaScript特有的怪癖; 在大多数语言中,不存在这种令人困惑的概念。

N (NaN)

It stands for “Not a Number”, and represents the absence of a valid number. It results from an invalid computation, such as an arithmetic operation on a string instead of a number. Let’s see a few examples.

它代表“非数字”,代表缺少有效数字 。 它是由无效计算导致的,例如对string而不是number的算术运算。 让我们看一些例子。

1 * 'five'
'ten' / 2

Output: NaN

输出: NaN

let myVar = 'four'
console.log( Math.sqrt(myVar) )

Output: NaN

输出: NaN

Note that due to type coercion, operations like ‘5’ * 5 or Math.sqrt(‘4’) are all valid in JavaScript. However, in cases where type coercion doesn’t apply, those operations will always yield NaN.

注意,由于类型强制, '5' * 5Math.sqrt('4')类的操作在JavaScript中均有效。 但是,在不应用类型强制的情况下,这些操作将始终产生NaN

Let’s examine a few quirks with this keyword.

让我们研究一下与此关键字有关的一些怪癖。

NaN == NaN

Output: false

输出: false

Sometimes it’s useful to find out if an operation is valid.

有时,找出某个操作是否有效很有用。

function checkIfValidOperation(operation){
if (operation === NaN)
console.log("Invalid Operation!");
else
console.log("Valid Operation!");
}let myOp = Math.sqrt('four'); //NaNcheckIfValidOperation(myOp) //???

Output: Valid Operation!

输出: Valid Operation!

Unexpected! Doesn’t myOp equal NaN!? Unfortunately, no. That’s because in JavaScript:

意外! myOp不等于NaN myOp 抱歉不行。 那是因为在JavaScript中:

NaN === NaN

NaN === NaN

Output: false

输出: false

This is one of the quirks of the language. In order to test if an operation yields NaN, we need to use the built-in function isNaN().

这是该语言的怪癖之一。 为了测试某个操作是否产生NaN ,我们需要使用内置函数isNaN()

isNaN(myOp);

Output: true

输出: true

结合所有 (Combining it all)

Combining our non-value trio, we can extract additional quirks such as:

结合我们的非价值三重奏,我们可以提取其他怪癖,例如:

1 + null + 1

Output: 2

输出2

null + null

null + null

Output: 0

输出: 0

That’s because null is treated like 0.

这是因为null被视为0

undefined + 1
null + undefined

Output: NaN

输出: NaN

That one is expected behavior.

那是预期的行为。

We can Summarise the above as follows:

我们可以总结如下:

  • undefined means that the variable exists (was declared), but its data type doesn’t, because it’s unassigned

    undefined表示变量存在(已声明),但其数据类型不存在,因为未分配

  • null means that the variable’s data type exists, but its value is purposely left empty

    null表示变量的数据类型存在,但有意将其值留空

  • null symbolizes nothing and is treated like 0

    null表示没有任何意义 ,被视为0

  • NaN means that an arithmetic operation is invalid

    NaN表示算术运算无效

  • It’s considered good practice to use the threequals operator (===) when comparing values to avoid type coercion

    比较值以避免类型强制转换时,最好使用threequals运算符(===)

Thank you for reading! Happy coding! :)

感谢您的阅读! 编码愉快! :)

翻译自: https://medium.com/@joseph.pyram/the-non-value-trio-of-javascript-db609004e3ec

javascript最大值


http://www.niftyadmin.cn/n/1468032.html

相关文章

java super构造函数_Java 构造函数,super,this,final,static

一、java 创建类是自动生成一个无参数的构造函数自定义构造函数:public 类名(参数列表){}注意:1、构造函数没有返回值2、构造函数名必须和类名一致3、构造函数的访问修饰符一定是public 否则无法实例化4、自定义构造函数时会替代 java 生成的构造函数&am…

React键的常见错误

When first learning React, it’s easy to get tripped up by simple mistakes. Even seasoned developers make mistakes.初学React时,很容易被简单的错误绊倒。 即使是经验丰富的开发人员也会犯错。 One area that is often misunderstood is how to use a key …

超级玛丽java下载_超级玛丽java源码 非本人原创 - 下载 - 搜珍网

压缩包 : SuperMario-master.zip 列表SuperMario-master/SuperMario-master/.classpathSuperMario-master/.projectSuperMario-master/.settings/SuperMario-master/.settings/org.eclipse.core.resources.prefsSuperMario-master/.settings/org.eclipse.jdt.core.prefsSuperMa…

java spring 源码下载_Spring1:Spring简介、环境搭建、源码下载及导入MyEclipse

框架学习前言这个模块是面向Spring的,Spring的学习我是这么想的:1、简单介绍Spring,主要是从网上借鉴一些重点2、尽量说明清楚Spring的使用方法以及细节点3、尽量以自己的理解讲清楚Spring中的一些源代码Spring是什么Spring是一款为了解决企业…

pycharm下配置jupyter_安装anaconda及pycharm 启动Jupyter

昨天重装系统之后记录了配置C环境,今天继续配置Python环境。这个anaconda好啊 有Jupyyter(一个浏览器界面的python,调试相当方便),具体优势见下面链接https://www.zhihu.com/question/27615938一/Anaconda的安装下载Anaconda安装包&#xff0…

python utc时间如何取整_如何在Djang中取整时区软件日期

我试图将默认时区datetime转换为localtime,并在Django视图中将时间取整为15分钟。我有以下循环时间函数:def roundTime(dtNone, dateDeltatimedelta(minutes1)):"""Round a datetime object to a multiple of a timedeltadt : datetime.d…

打字机运行时验证

技术 (TECHNOLOGY) 问题 (The Problem) Every time our application receives some data input via an application boundary at runtime, it should be at least validated against a data scheme. In typed languages like Typescript, it also makes sense to map the input…

通过angular cli混合应用程序将angularjs迁移到angular

The purpose of this tutorial is to provide another way to do the migration from an AngularJS application to the latest version of Angular. At the time that this guideline was done, Angular is at the version 9.本教程的目的是提供从AngularJS应用程序迁移到最新…