让我们讨论一下变量,以及为什么要在JavaScript中使用它们。
by Zell Liew
由Zell Liew
让我们讨论一下变量,以及为什么要在JavaScript中使用它们。 (Let’s talk about variables — and why you should use them in JavaScript.)
The main purpose of coding is to solve problems. For example, what happens when you click on a button? That’s a problem for us to solve.
编码的主要目的是解决问题。 例如,当您单击按钮时会发生什么? 这是我们要解决的问题。
So, let’s begin this article by solving a simple problem.
因此,让我们从解决一个简单的问题开始。
数苹果 (Counting apples)
If you have 4 apples and you buy 27 more, how many apples do you have? Take a second and write your answer in your text editor.
如果您有4个苹果,又购买了27个,那么您有多少个苹果? 花一点时间,然后在文本编辑器中写下您的答案。
What’s your answer?
你的答案是什么?
// This? 31
// Or this? 4 + 27
Both answers are right, but the second method is better — because you’re offloading the calculation to JavaScript. You’re teaching it how to arrive at the answer.
两种答案都是正确的,但是第二种方法更好-因为您将计算工作转移到了JavaScript。 您正在教它如何得出答案。
But there’s still one problem with the code.
但是代码仍然存在一个问题。
If you look at 4 + 27
without any context from our apple problem, do you know we’re calculating the number of apples you’re currently holding?
如果您在4 + 27
情况下没有遇到苹果问题,那么您是否知道我们正在计算您当前持有的苹果数量?
Probably not.
可能不是。
So, a better way is to use algebra to substitute 4 and 27 with variables. When you do so, you’ll get the ability to write code that has meaning:
因此,更好的方法是使用代数将4和27替换为变量。 这样做时,您将能够编写具有以下含义的代码:
initialApples + applesBought
The process of substituting 4 with a variable called initialApples
is called declaring variables.
用名为initialApples
的变量替换4的过程称为声明变量。
声明变量 (Declaring variables)
You declare variables with the following syntax:
您可以使用以下语法声明变量:
const variableName = 'value'
There are four parts you’ll want to take note of:
您需要注意四个部分:
The
variableName
variableName
The
value
value
The
=
sign=
符号The
const
keywordconst
关键字
variableName (The variableName)
variableName
is the name of the variable you’re declaring. You can name it anything, as long as it follows these rules:
variableName
是您要声明的变量的名称。 您可以为它命名,只要遵循以下规则即可:
- It must be one word必须是一个字
It must consist only of letters, numbers, or underscores (0–9, a-z, A-Z,
_
).它只能包含字母,数字或下划线(0–9,az,AZ,
_
)。- It cannot begin with a number.它不能以数字开头。
It cannot be any of these reserved keywords
不能是这些保留关键字中的任何一个
If you need to use two or more words to name your variable, just join the words together but capitalize the first letter of each subsequent word. This weird capitalization is called camel case.
如果需要使用两个或多个单词来命名变量,只需将单词连接在一起,但将每个后续单词的首字母大写。 这种奇怪的大小写被称为骆驼案 。
A good example of a camel-cased variable is applesToBuy
.
驼峰式变量的一个很好的例子是applesToBuy
。
价值 (The value)
The value is what you want the variable to be. It can be primitives (like strings and numbers) or objects (like arrays and functions).
该值是您希望变量成为的值。 它可以是原语(如字符串和数字)或对象(如数组和函数)。
=在JavaScript中 (= in JavaScript)
=
in JavaScript doesn’t work like =
in math. Don’t get confused.
JavaScript中的=
不能像数学中的=
一样工作。 不要感到困惑。
In JavaScript, =
means assignment. When you use =
, you set (or assign) the value on the right hand side (RHS) of the =
sign to the left hand side (LHS) of the =
sign.
在JavaScript中, =
表示赋值 。 当您使用=
,设置(或指定)的值的右手边(RHS) =
标志的左手侧(LHS) =
迹象。
In the following statement, you set the variable initialApples
to the number 4.
在下面的语句中,将变量initialApples
设置为数字4。
const initialApples = 4
If you console.log
this variable, you can see that initialApples
is 4.
如果使用console.log
这个变量,则可以看到initialApples
为4。
console.log(initialApples) // 4
作业前评估 (Evaluation before assignment)
Every variable can only take up one value. So, if you have an equation that needs to be evaluated on the RHS, it will be evaluated before it is assigned to the variable.
每个变量只能占用一个值。 因此,如果您有一个需要在RHS上求值的方程式,则在将其分配给变量之前将对其求值。
const initialApples = 4 const applesToBuy = 27 const totalApples = initialApples + applesToBuy
In this example, JavaScript will evaluate the answer of initialApples
+ applesToBuy
(which results in 31) before assigning the results to totalApples
. This is why you get 31
if you try to log totalApples
.
在此示例中,JavaScript在将结果分配给totalApples
之前,将评估initialApples
+ applesToBuy
的答案(结果为31)。 这就是为什么如果尝试记录totalApples
得到31
totalApples
。
console.log(totalApples) // 31
const关键字 (The const keyword)
const
is one of three keywords you can use to declare variables. There are two other keywords – let
and var
.
const
是可用于声明变量的三个关键字之一。 还有另外两个关键字– let
和var
。
All three keywords declare variables, but they’re slightly different from each other.
所有这三个关键字都声明了变量,但它们之间略有不同。
const vs let vs var (Const vs let vs var)
const
and let
are keywords made available to us in ES6. They are better for creating variables than var
because they’re block scoped while var is function scoped.
const
和let
是ES6中提供给我们的关键字。 它们比var
更好地创建变量,因为它们是块作用域的,而var是函数作用域的 。
For now, let’s concentrate on the difference between const
and let
.
现在,让我们集中讨论const
和let
的区别。
const vs let (Const vs let)
If you declare a variable with const
, you cannot reassign it with a new value. The following code produces an error:
如果使用const
声明变量, 则无法使用新值重新分配 它 。 以下代码产生错误:
const applesToBuy = 22
// Reassigning to a variable declared with const results in an error applesToBuy = 27
If you declare a variable with let
, you can reassign it with a new value.
如果使用let
声明变量,则可以使用新值重新分配它。
let applesToBuy = 22 applesToBuy = 27 console.log(applesToBuy)
您应该使用const还是let? (Should you use const or let?)
Understanding whether you should use const
or let
is more of an advanced topic.
了解是应该使用const
还是let
是更高级的主题。
When you’re starting out, using let
would be much simpler than using const
.
当您刚开始时,使用let
将比使用const
简单得多。
However, as you write more programs, you’ll slowly realize that you want to refrain from reassigning your variables. So you’ll begin to use const
over let
. But that’s a different topic for another day.
但是,随着编写更多程序,您将逐渐意识到,您希望避免重新分配变量。 因此,您将开始在let
上使用const
。 但这又是另一回事。
Since you’re going to use const
over let
anyway when you write more advanced programs, it’s better to get into the habit of preferring const
over let
when you’re starting out.
由于在编写更高级的程序时无论如何都要使用const
over let
,因此最好在开始时养成更喜欢const
不是let
的习惯。
In case you’re wondering, don’t use var
anymore — there’s no need for it. let
and const
are much better than var
.
如果你想知道,不要使用var
了-有没有必要为它。 let
和const
比var
好得多。
结语 (Wrapping up)
In JavaScript, variables are used to hold a value. They can hold any value, from primitives to objects.
在JavaScript中,变量用于保存值。 它们可以保存任何值,从基元到对象。
The =
sign in JavaScript isn’t the same as the =
sign in Math. In JavaScript, =
means assignment.
该=
在JavaScript标志是不一样的=
数学符号。 在JavaScript中, =
表示赋值。
When you declare variables, use camelCase to name your variables. Avoid the reserved keywords.
声明变量时,请使用camelCase命名变量。 避免使用保留关键字。
You can declare variables with either const
, let
or var
. As much as possible, you’ll want to use const
over let
. Use let
when you need to reassign values. There’s no longer a need to use var
.
您可以使用const
, let
或var
声明变量。 尽可能多地使用const
over let
。 当您需要重新分配值时,请使用let
。 不再需要使用var
。
This article is a sample lesson from Learn JavaScript — a course that helps you learn JavaScript and build real, practical components from scratch. If you found this article helpful, I invite you to find out more about Learn JavaScript.
本文是学习JavaScript的示例课程,该课程可帮助您学习JavaScript并从头开始构建实际的实用组件。 如果您觉得这篇文章对您有帮助,我邀请您查找有关Learn JavaScript的更多信息 。
(Oh, by the way, if you liked this article, I’d appreciate it if you could share it. ?)
(哦,顺便说一句,如果您喜欢这篇文章,如果可以分享的话 ,不胜感激。)
Originally published at zellwk.com.
最初在zellwk.com上发布。
翻译自: https://www.freecodecamp.org/news/lets-talk-about-variables-and-why-you-should-use-them-in-javascript-92d8c661a5b/
相关文章:

Services(服务)
开启服务有两种方式: 如果不会可以看老师的百度音乐盒的案例1、start方式:start方式的生命周期:*服务只会被开启一次,直到用户手动停止 服务才会被销毁*开启需要调用startService 会执行onCreate(),onStartCommand() *注&…

[敏捷开发实践](2) 用于开发和维持复杂产品的敏捷开发框架Scrum
[敏捷开发实践](2) 用于开发和维持复杂产品的敏捷开发框架Scrum 1,Scrum概述 上篇中提到敏捷开发有两种主流的方法,一个是XP,另一个是Scrum,本篇简要介绍Scrum方法。Scrum是一套开发和维护复杂产品的框架或…
js 实现多选框(复选框) 和单选框,下拉框功能完整示例代码附效果图
<!DOCTYPE html> <html><head><meta charset"utf-8" /><script src"http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script><title>单选框,复选框,下拉菜单简单示例</title></head…

ruby on rails_我成为了Ruby on Rails和React的贡献者,你也可以
ruby on railsI am really grateful to have contributed to a few open source projects, including two I currently use on a regular basis: Ruby on Rails and React.我非常感谢为一些开源项目做出了贡献,其中包括我目前定期使用的两个项目: Ruby o…

MySQL加密算法
1.不可逆加密: PASSWORD(),ENCRYPT(,),MD5(),SHA5()。 2.可逆的加密算法: ENCODE(,) DECODE(,):加密解密字符串。该函数有两个参数:被加密或解密的字符串和作为加密或解密基础的密…

js回调函数和函数带参数的使用示例
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 //demo1 <html><head><meta charset"UTF-8"><script src"http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script></head>&…

mvc-3模型和数据(1)
MVC和命名空间 var User function(atts) {this.attribute atts || {}; } //和具体user相关的方法 User.prototype.destroy function() {}; //和具体user不相关的函数和变量 User.fetchRemove function() {}; var user new User({name:jinks}); user.destroy();构建对象关系…

初步了解:使用JavaScript进行表达式(De Do Do Do,De Da Da Da)
by Donavon West由Donavon West 初步了解:使用JavaScript进行表达式(De Do Do Do,De Da Da Da) (A first look: do expressions in JavaScript (De Do Do Do, De Da Da Da)) This article is not about about the The Police’s 1980 hit song from alb…

div 下 的img水平居中
设置text-align:center; 这个div必须要设置宽度; 如:{text-align:center; width:100%;}转载于:https://www.cnblogs.com/zzd0916/p/6626772.html

Understanding SOAP
Understanding SOAP转载于:https://www.cnblogs.com/daishuguang/p/4227983.html

js删除组数中的某一个元素(完整代码附效果图)
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: <view class"big-logos"> <imagebindtap"addimg"src../../../image/s.png></image> <blockwx:for"{{img_arr}}"wx:key"in…

c专家编程/c陷阱_如何避免常见的初学者陷阱并像专家一样开始编码
c专家编程/c陷阱by Dmitri Grabov德米特里格拉波夫(Dmitri Grabov) 如何避免常见的初学者陷阱并像专家一样开始编码 (How to avoid common beginner pitfalls and start coding like a pro) Learning to code is tough. We’ve all encountered cryptic errors and code break…

xmpp关于后台挂起的消息接收,后台消息推送,本地发送通知
想问下,在xmpp即时通讯的项目中,我程序如果挂起了,后台有消息过来,我这边的推送不过来,所以我的通知就会收不到消息,当我重新唤醒应用的时候,他才会接收到通知,消息就会推送过来&…

[冲昏头脑]IDEA中的maven项目中学习log4j的日志操作
第一,你要有log4j的对应的包,由于我用的maven,所以直接在pom.xml文件依赖下载则可,如你尚为有此包,请自行百度下载导入,或上http://www.mvnrepository.com/搜索。上如则是我的log4j的包的版本。好了&#x…

女神推荐, 卡片,广告图 ,点击查看更多
微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文: <view><view classtitle>女神推荐 </view> <image stylemargin-top:25rpx; classtab_img src{{img list_data.q1[1].image}}></image><view classv…

aws lambda_恐怕您正在考虑AWS Lambda的冷启动完全错误
aws lambdaby Yan Cui崔燕 恐怕您正在考虑AWS Lambda的冷启动完全错误 (I’m afraid you’re thinking about AWS Lambda cold starts all wrong) When I discuss AWS Lambda cold starts with folks in the context of API Gateway, I often get responses along the line of…

python tkinter窗口弹出置顶的方法
加上下面两句即可实现root窗口的置顶显示,可以用于某些程序的消息提示,能够弹出到桌面显示 root Tk() root.wm_attributes(-topmost,1) 转载于:https://www.cnblogs.com/shuchengxiang/p/6632140.html
用Quartus II Timequest Timing Analyzer进行时序分析 :实例讲解 (一)
一,概述 用Altera的话来讲,timequest timing analyzer是一个功能强大的,ASIC-style的时序分析工具。采用工业标准--SDC(synopsys design contraints)--的约束、分析和报告方法来验证你的设计是否满足时序设计的要求。在…

软件工程与软件测试基础知识_这是我在软件工程工作九个月中学到的知识
软件工程与软件测试基础知识I’ve been working for about nine months at Dexter as a software developer. I wrote a blog post about landing the job initially, as well as a technical post about a self positioning component I made in my first couple of months at…

[bzoj1064][Noi2008]假面舞会
题意:有n个人,每个人都有一个标号,每种标号的人只能看见下一个标号的人(最后一种标号看见第一种),给定m个关系,求这个关系是否合法以及合法情况下最大和最小的方案数。$n\leqslant 10^{5},m\leqslant 10^{6…

js取一定范围内的随机整数
Math.floor(Math.random()*305 1); Math.random()*305 的作用是取0到305的随机数 加1 就是1到305的随机数, Math.floor是取整数, 所以最后的结果是0到305的随机整数 微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。

AE,按照属性值关系选择要素
if(axMapControl2.LayerCount<0) { MessageBox.Show("请加载图层后使用该功能","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); } else { ILayer pLayer axMapControl2.get_Layer(0); IFeatureLayer pFeatureLayer pLayer as IFeatureLay…

aws lambda使用_如何使用AWS Lambda和S3构建无服务器URL缩短器
aws lambda使用by Daniel Ireson丹尼尔埃里森(Daniel Ireson) 如何使用AWS Lambda和S3构建无服务器URL缩短器 (How to build a Serverless URL shortener using AWS Lambda and S3) Throughout this post we’ll be building a serverless URL shortener using Amazon Web Ser…

android -volley-请求数据
private List<gson.DataBean>arrGson;//请求的数据 //请求数据的方法 public void initData() { RequestQueue mQueue Volley.newRequestQueue(getApplicationContext()); String url "http://www.fashions88.com/you/HBooks88/GetBooks88Data…

[微信小程序]动画,从顶部掉花的效果(完整代码附效果图)
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: image{ width: 100rpx;height: 100rpx;position: absolute;top: -100rpx; } 如果对您有帮助,请关注我,欢迎加入微信小程序开发交流QQ群(173683866&…

pl/sql developer连接远程数据库
本地不安装oracle client程序,直接使用pl/sql developer连接远程数据库 考虑到机子本身资源有限,一个client会占用很多资源,尝试使用不安装客户端的方式进行远程连接。 需要软件:instantclient-basic-win32-10.2.0.5.zip、pl/sql …

工厂用抽象类比接口_用简单的现实类比解释硬编码概念
工厂用抽象类比接口by Samer Buna通过Samer Buna 用简单的现实类比解释硬编码概念 (Hard Coding Concepts Explained with Simple Real-life Analogies) 如何向5岁的孩子解释诸如流,promise,lint和声明性编程之类的编码概念 (How to explain coding con…

[微信小程序]点击切换卡片动画效果
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 先上效果图, GIF: <!--pages/roll/roll.wxml--> <!-- 单身 --> <block wx:if"{{danshen}}"><view class"card_wrap"><view animatio…

redis学习之——Redis事务(transactions)
Redis事务:可以一次执行多个命令,本质是一组命令的集合。一个事务中的,所有命令都会序列化,按顺序地串行化执行而不会被其它命令插入,不许加塞。 常用命令:MULTI 开启事务 EXEC 提交事务、 DISCARD 放弃…

WordPress页面Page和文章Post的相互转换
1. 进入phpMyAdmin; 2. 进入WordPress对应的数据库; 3. 浏览wp_posts数据表; 4. 找到相应的 页面Page 并编辑(找到相应的 文章Post 并编辑); 5. 修改 post_type 为 post(page)&#…