JavaScript数据类型:Typeof解释

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well.

typeof是一个JavaScript关键字,当您调用它时将返回变量的类型。 您可以使用它来验证函数参数或检查是否定义了变量。 还有其他用途。

The typeof operator is useful because it is an easy way to check the type of a variable in your code. This is important because JavaScript is a is a dynamically typed language. This means that you aren’t required to assign types to variables when you create them. Because a variable is not restricted in this way, its type can change during the runtime of a program.

typeof运算符很有用,因为它是检查代码中变量类型的简便方法。 这很重要,因为JavaScript是一种动态类型的语言 。 这意味着在创建变量时不需要为变量分配类型。 因为不以此方式限制变量,所以其类型可以在程序运行时更改。

For example:

例如:

var x = 12345; // number
x = 'string'; // string
x = { key: 'value' }; // object

As you can see from the above example, a variable in JavaScript can change types throughout the execution of a program. This can be hard to keep track of as a programmer, and this is where the typeof operator is useful.

从上面的示例可以看到,JavaScript中的变量可以在程序执行期间更改类型。 作为程序员可能很难跟踪,这就是typeof运算符有用的地方。

The typeof operator returns a string that represents the current type of a variable. You use it by typing typeof(variable) or typeof variable. Going back to the previous example, you can use it to check the type of the variable x at each stage:

typeof运算符返回一个表示变量当前类型的字符串。 您可以通过键入typeof(variable)typeof variable来使用它。 回到上一个示例,您可以在每个阶段使用它来检查变量x的类型:

var x = 12345; 
console.log(typeof x) // number
x = 'string'; 
console.log(typeof x) // string
x = { key: 'value' };
console.log(typeof x) // object

This can be useful for checking the type of a variable in a function and continuing as appropriate.

这对于检查函数中变量的类型并酌情继续操作很有用。

Here’s an example of a function that can take a variable that is a string or a number:

这是一个函数示例,该函数可以采用字符串或数字作为变量:

function doSomething(x) {if(typeof(x) === 'string') {alert('x is a string')} else if(typeof(x) === 'number') {alert('x is a number')}
}

Another way the typeof operator can be useful is by ensuring that a variable is defined before you try to access it in your code. This can help prevent errors in a program that may occur if you try to access a variable that is not defined.

typeof运算符有用的另一种方式是,在尝试在代码中访问变量之前,确保已定义了变量。 如果您尝试访问未定义的变量,这可以帮助防止程序中可能发生的错误。

function(x){if (typeof(x) === 'undefined') {console.log('variable x is not defined');return;}// continue with function here...
}

The output of the typeof operator might not always be what you expect when you check for a number.Numbers can turn in to the value NaN (Not A Number) for multiple reasons.

当检查数字时, typeof运算符的输出可能并不总是您期望的。 数字可能由于多种原因而变成值NaN(非数字) 。

console.log(typeof NaN); //"number"

Maybe you tried to multiply a number with an object because you forgot to access the number inside the object.

也许您试图将一个对象与一个数字相乘,因为您忘记了访问该对象内部的数字。

var x = 1;
var y = { number: 2 };
console.log(x * y); // NaN
console.log(typeof (x * y)); // number

When checking for a number, it is not sufficient to check the output of typeof for a number, since NaN alsopasses this test.This function check for numbers, and also doesn’t allow the NaN value to pass.

当一个号码的检查,这是不够的,检查的输出typeof的数量,因为NaN alsopasses的人数这个test.This功能检查,也不允许NaN值传递。

function isNumber(data) {return (typeof data === 'number' && !isNan(data));
}

Even thought this is a useful validation method, we have to be careful because javascript has some weird parts and one of them is the result of typeof over particular instructions. For example, in javascript many things are just objects so you’ll find.

即使认为这是一种有用的验证方法,我们也要小心,因为javascript有一些奇怪的部分,其中之一是typeof over特定指令的结果。 例如,在javascript中,很多东西都只是objects所以您会发现。

var x = [1,2,3,4]; 
console.log(typeof x)  // objectconsole.log(typeof null)  // object

更多信息: (More Information:)

MDN Documentation for typeof

有关typeof的MDN文档

翻译自: https://www.freecodecamp.org/news/javascript-data-types-typeof-explained/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390959.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

asp.net读取用户控件,自定义加载用户控件

1、自定义加载用户控件 ceshi.aspx页面 <html><body> <div id"divControls" runat"server"></div> </body></html> ceshi.aspx.cs页面 System.Web.UI.UserControl newUC (System.Web.UI.UserControl)Page.LoadContro…

配置Java_Home,临时环境变量信息

一、内容回顾 上一篇博客《Java运行环境的搭建---Windows系统》 我们说到了配置path环境变量的目的在于控制台可以在任意路径下都可以找到java的开发工具。 二、配置其他环境变量 1. 原因 为了获取更大的用户群体&#xff0c;所以使用java语言开发系统需要兼容不同版本的jdk&a…

网页缩放与窗口缩放_功能缩放—不同的Scikit-Learn缩放器的效果:深入研究

网页缩放与窗口缩放内部AI (Inside AI) In supervised machine learning, we calculate the value of the output variable by supplying input variable values to an algorithm. Machine learning algorithm relates the input and output variable with a mathematical func…

在构造器里调用可重写的方法有什么问题?

问题&#xff1a;在构造器里调用可重写的方法有什么问题&#xff1f; 我有一个检票页面的类通过抽象方法的结果去去设置页的标题 public abstract class BasicPage extends WebPage {public BasicPage() {add(new Label("title", getTitle()));}protected abstract…

创建hugo博客_如何创建您的第一个Hugo博客:实用指南

创建hugo博客Hugo is a great tool to use if you want to start a blog.如果您想创建博客&#xff0c;Hugo是一个很好的工具。 I use Hugo myself for my blog, flaviocopes.com, and Ive been using it for more than two years. I have a few reasons for loving Hugo.我本…

Python自动化开发01

一、 变量变量命名规则变量名只能是字母、数字或下划线的任意组合变量名的第一个字符不能是数字以下关键字不能声明为变量名 [and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not,…

记录关于vs2008 和vs2015 的报错问题

出现了 VS2008无法创建项目&#xff0c;无法打开项目的情况&#xff0c;提示这个注册表键值有问题 HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ MSBuild \ ToolsVersions \ 14.0&#xff0c; 但是查看了注册表没有这个键。费尽辛万苦&#xff0c;中午在思密达的一个网站上看到…

未越狱设备提取数据_从三星设备中提取健康数据

未越狱设备提取数据Health data is collected every time you have your phone in your pocket. Apple or Android, the phones are equipped with a pedometer that counts your steps. Hence, health data is recorded. This data could be your one free data mart for a si…

怎么样用System.out.println在控制台打印出颜色

问题&#xff1a;怎么样用System.out.println在控制台打印出颜色 怎么样才能在控制台里打印颜色啊&#xff1f;我想要展示一些有颜色的字体&#xff0c;当处理器发送数据和接收数据的时候&#xff0c;也使用不同颜色的字体。 回答一 在这个Java类里面带有public static 的数…

sql注入语句示例大全_SQL Order By语句:示例语法

sql注入语句示例大全Order By is a SQL command that lets you sort the resulting output from a SQL query.Order By是一个SQL命令&#xff0c;可让您对SQL查询的结果输出进行排序。 订购依据(ASC&#xff0c;DESC) (Order By (ASC, DESC)) ORDER BY gives us a way to SORT…

[BZOJ2599][IOI2011]Race 点分治

2599: [IOI2011]Race Time Limit: 70 Sec Memory Limit: 128 MBSubmit: 3934 Solved: 1163[Submit][Status][Discuss]Description 给一棵树,每条边有权.求一条简单路径,权值和等于K,且边的数量最小.N < 200000, K < 1000000 Input 第一行 两个整数 n, k第二..n行 每行三…

分词消除歧义_角色标题消除歧义

分词消除歧义折磨数据&#xff0c;它将承认任何事情 (Torture the data, and it will confess to anything) Disambiguation as defined in the vocabulary.com dictionary refers to the removal of ambiguity by making something clear and narrowing down its meaning. Whi…

北航教授李波:说AI会有低潮就是胡扯,这是人类长期的追求

这一轮所谓人工智能的高潮&#xff0c;和以往的几次都有所不同&#xff0c;那是因为其受到了产业界的极大关注和参与。而以前并不是这样。 当今世界是一个高度信息化的世界&#xff0c;甚至我们有一只脚已经踏入了智能化时代。而在我们日常交流和信息互动中&#xff0c;迅速发…

创建字符串枚举的最好方法

问题&#xff1a;创建字符串枚举的最好方法 用一个枚举类型去表示一组字符串的最好方法是什么 我尝试这样&#xff1a; enum Strings{STRING_ONE("ONE"), STRING_TWO("TWO") }我怎么样才可以像使用字符串那样使用它们&#xff1f; 回答一 我不知道你想…

网络安全习惯_健康习惯,确保良好的网络安全

网络安全习惯In a similar fashion to everyone getting the flu now and again, the risk of catching a cyberattack is a common one. Both a sophisticated social engineering attack or grammatically-lacking email phishing scam can cause real damage. No one who c…

attr和prop的区别

由于prop(property的缩写)和attr(attribute的缩写)翻译成汉语&#xff0c;均有“特性、属性”等意思的原因&#xff0c;导致大家容易混淆分不清。 (1)在处理自定义时属性时&#xff0c;用attr()&#xff0c;若用prop(),则结果为undefined&#xff1b; (2)DOM固有属性&#xff0…

15行Python代码,帮你理解令牌桶算法

在网络中传输数据时&#xff0c;为了防止网络拥塞&#xff0c;需限制流出网络的流量&#xff0c;使流量以比较均匀的速度向外发送&#xff0c;令牌桶算法就实现了这个功能&#xff0c;可控制发送到网络上数据的数目&#xff0c;并允许突发数据的发送。 什么是令牌 从名字上看令…

在Java中,如何使一个字符串的首字母变为大写

问题&#xff1a;在Java中&#xff0c;如何使一个字符串的首字母变为大写 我使用Java去获取用户的字符串输入。我尝试使他们输入的第一个字符大写 我尝试这样: String name;BufferedReader br new InputStreamReader(System.in);String s1 name.charAt(0).toUppercase());…

在加利福尼亚州投资于新餐馆:一种数据驱动的方法

“It is difficult to make predictions, especially about the future.”“很难做出预测&#xff0c;尤其是对未来的预测。” ~Niels Bohr〜尼尔斯波尔 Everything is better interpreted through data. And data-driven decision making is crucial for success in any ind…

javascript脚本_使用脚本src属性将JavaScript链接到HTML

javascript脚本The ‘src’ attribute in a tag is the path to an external file or resource that you want to link to your HTML document.标记中的src属性是您要链接到HTML文档的外部文件或资源的路径。 For example, if you had your own custom JavaScript file named …