Variables
Valid Variable Name 合法的变量名
- employee_77
- Variable_name
- x
- Name_code
- name_code
- _emp_name
Invalid Variable Name 非法的变量名
- var // var is reserve word.
- 77employee // Initial character is a number.
- Variable%name // % character is not allowed.
- Name&code // & is not allowed.
Declaring Variables
With the keyword var, followed by name of the variable.
var emp_name
The above syntax can be used to declare both local and global variables.
Another way to declare a variable is simply assigning it a value.
x=12.2 emp_code = 'E123'
// Declaring a variable // Best Practices var emp_code = 'E123'; // Poor Practices emp_code = 'E123' // Declaring multiple variables. Use one var statement and declare each variable on a new line. // Best Practices var emp_list = emplist(), x = 12, str1 = 'String1'; // Poor Practices var emp_code = emplist(); var x = 12 ; var str1 = 'String1'; // Declare unassigned variables last. // Best Practices var roll_no = 12, name, class; // Poor Practices var name class, roll_no = 12;
Evaluating Variables
A variable or array element that has not been assigned a value, has the value undefined.
The result of evaluating an unassigned variable depends on how it was declared:
If the unassigned variable was declared with var, the evaluation results in the undefined value or NaN in numeric contexts.
If the unassigned variable is declared without var statement, the evaluation results in a run time error.
一个变量或者数组元素没有被分配初始值,其值为undefined
未赋值变量的值取决于这个变量是怎么声明的
如果未赋值变量是通过var进行声明的,则它的值为undefined或者NaN
如果未赋值变量没有使用var进行定义,在执行表达式的过程中将发生运行时异常
See the following statements :
var x; print("The value of x is : " + x); // prints "The value of x is : undefined" print("The value of y is : " + y); // throws reference error exception
You can use undefined to determine whether a variable has a value.
In the following statements, the variable x is not assigned a value, and the if statement evaluates to true.
var x; if(x === undefined) { do something ; } else { do something ; }
Variables Scope
The variables can be declared and used in two ways locally and globally.
When you declare a JavaScript variable within a function, it is called a local variable because the variable is available only within the function.You can use same variable name within different function.
When you declare a variable outside a function it is called global variable.You can optionally declare a global variable using var (for example var empCode).
However, you must use var to declare a variable inside a function.
变量的定义和使用分两种:局部变量和全局变量
如果在函数中定义变量,则该变量是局部变量,它只在函数体类有效
不同的函数中,可以定义相同名称的变量,互不影响
在函数体外可以随意的通过var关键字定义的变量,称为全局变量
尽管如此,在函数内部声明变量时,必须使用var进行声明
(注意:函数的参数除外,而且函数的参数不能用var声明)
Check whether a variable is defined or not in JavaScript
To check whether a variable is defined or not, you can use the typeof operator.
The following alert will return "undefined" i.e. the variable "abc" is not defined.
if (typeof abc === 'undefined') { // variable abc is undefined }
检查一个变量是否已经定义,通过typeof进行判断
如果未定义,则typeof(x)==="undefined"
如果未定义,直接alert(x),将抛异常
如果已经定义,但未分配值,则x===undefined
如果已经定义,且已分配至,则类型为值所对应的类型
var x; alert(x===undefined);//true alert(typeof(x)==="undefined");//true var a = 1; alert(typeof(a)==="number");//true showType(typeof(a)); var b = ""; alert(typeof(b)==="string");//true showType(typeof(b)); var c = []; alert(typeof(c)==="object");//true showType(typeof(c)); var d = {}; alert(typeof(d)==="object");//true showType(typeof(d)); var e = function() {alert("i am a fn");}; alert(typeof(e)==="function");//true showType(typeof(e)); function showType(type) { switch(type) { case "number": alert("type is number"); break; case "string": alert("type is string"); break; case "function": alert("type is function"); break; case "object": alert("type is object"); break; default: alert("wrong type!"); break; } }
Constants
In JavaScript, constants are declared with const keyword and assigned at the time of the declaration. A constant can be global or local to a function where it is declared
Constants are read-only, therefore you can not modify them later on.
Naming a constant in JavaScript follow the same rule of naming a variable except that the const keyword is always required, even for global constants.
If the keyword is omitted, the identifier is assumed to represent a variable.
JavaScript中,常量在声明时便初始化赋值。
常量可以是全局的或者局部的。
常量是只读的,一旦声明,后面都不能再改变。
常量定义使用的关键字const 必须写,如果省略,将被认为是普通变量定义。
在同一个作用范围内,不要定义同名的常量或者变量。下面的语法将导致错误。
const country = 'India'; //You cannot declare a constant with the same name as a function // or variable in the same scope. Following statements create error. function abc() { const abc = 55; } function abc() { const x = 15; var x; }
同一个范围内,如果出现同名的变量或者函数,后者会覆盖前者;
但是,对于常量,后者无法覆盖前者,只要前者是以常量方式定义的,其值就不会再变。
var country = "EN"; const country = "US"; alert(country);// US
const country = "EN"; const country = "US"; alert(country); //EN
Data Type
JavaScript recognizes the following types of values
String: "google.com", 'yahoo.com'
Numbers:45, 45887, -45, 12.23, -145.55
Logical (Boolean):true, false
null:empty value or nothing. Since JavaScript is case-sensitive, null is not the same as Null, NULL
undefined:whose value is undefined
Data Type Conversion
JavaScript is a dynamically typed language.
Therefore there is no need to specify the data type of a variable at the time of declaring it.
Data types are converted automatically as needed during script execution.
JavaScript 是一门动态语言
因此在变量声明时,不需要指定其具体类型
数据类型在脚本执行的时候将自动转换
var age = 21; age = "What is your age?";
x = "What is your age ?" + 21 // returns "What is your age ?21 " y = 21 + " is my age. " // returns "21 is my age." "21" - 7 // returns 14 "21" + 7 // returns "217" "21" + "7" // returns "217" "21" * 7 // returns 147 "21" / 7 // returns 3
Array literals
In Javascript an array literal is a list of expressions, each of which represents an array element, enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified. If no value is supplied it creates an empty array with zero length.
//Creating an empty array : var fruits = [ ]; //Creating an array with four elements. var fruits = ["Orange", "Apple", "Banana", "Mango"]; //Creating an empty array that has 5 elements. var fruits = [5];
使用new关键字来创建数组
var fruits = new Array("Orange", "Apple", "Banana", "Chery");
Comma in array literals
There is no need to specify all elements in an array literal. If we put two commas in a row at any position in an array then an unspecified element will be created in that place.
The following example creates the fruits array :
fruits = ["Orange", , "Mango"]This array has one empty element in the middle and two elements with values. ( fruits[0] is "Orange", fruits[1] is set to undefined, and fruits[2] is "Mango").
If you include a single comma at the end of the elements, the comma is ignored. In the following example, the length of the array is two. There is no fruits[2].
fruits = ["Orange", "Mango",]
In the following example, the length of the array is four, and fruits[0] and fruits[2] are undefined.
fruits = [ , 'Apple', , 'Orange'];
Integer literals
1. Decimal ( base 10)
Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading zeros.
Example : 123, -20, 12345
2. Hexadecimal ( base 16)
Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal.
Example : 7b, -14, 3039
3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number is octal.
Example : 173, -24, 30071
Floating number literals
A floating number has the following parts.
- A decimal integer. 整数位
- A decimal point ('.'). 小数点
- A fraction. 小数位
- An exponent. 幂
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-").
- 8.2935
- -14.72
- 12.4e3 [ Equivalent to 12.4 x 103 ]
- 4E-3 [ Equivalent to 4 x 10-3 => .004 ]
Boolean literals
The Boolean type has two literal values :
- true
- false
Object literals
An object literal is zero or more pairs of comma separated list of property names and associated values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:
1. An object literal without properties:
var userObject = {}
2. An object literal with a few properties :
var student = {
First-name : "Suresy",
Last-name : "Rayy",
Roll-No : 12
};
Object literals maintain the following syntax rules:
- There is a colon (:) between property name and value. 属性名与值用冒号分割
- A comma separates each property name/value from the next.不同键值对用逗号分割
- There will be no comma after the last property name/value pair.最后一个键值对不跟逗号
String literals
JavaScript has its own way to deal with string literals. A string literal is zero or more characters, either enclosed in single quotation (') marks or double quotation (") marks.
You can also use + operator to join strings. The following are the examples of string literals :
- string1 = "w3resource.com"
- string1 = 'w3resource.com'
- string1 = "1000"
- string1 = "google" + ".com"
In addition to ordinary characters, you can include special characters in strings, as shown in the following table.
string1 = "First line. \n Second line."
相关推荐
- Programming basics: variables, loops, functions, etc. - Objects, classes, methods, and messages - Pointers, addresses, and memory management with ARC - Properties and Key-Value Coding (KVC) - ...
44. **Data type too large: exceeds 2GB** - 错误描述:数据类型过大:超过 2GB。 - 解决方法:考虑使用更小的数据类型或优化数据结构。 45. **Declaration of <Name> differs from previous declaration** - ...
Lesson 4 - Variables and expressions: giving names and values to things Lesson 5 - Object types and statements of code 46 Lesson 6 - Capstone project: your first Python program-convert hours to ...
Javascript循环,条件和对象分配:目标这是多伦多大学历史系教授的数字人文课程“一项任务。 如果您是一名老师,请随意为自己的课程分叉并重新利用。 如果您是学生,请继续阅读! 您不必成为一名编码人员即可在本...
在前端开发领域,CSS Variables(也称为CSS自定义属性)是一种强大的工具,它允许开发者在整个样式表中定义和重用变量。PostCSS 是一个JavaScript工具,它可以解析CSS,执行一些任务,然后输出新的CSS。Postcss-css-...
脚本运行位于德沃伦的航站楼内的空中交通管制员杂志(Als je de code wil runnen kun je dit doen door het volgende): nodemon variables.js Als je wisselt van bestand moet je nodemon eerst stoppen(ctr
PostCSS降级变量 用于降级CSS变量的插件。 : root { --primary-background : # fff ; --green-color : # 0f0 ;}. class { background : var ( --primary-background ); background-image : linear-gradient (to top ...
3rd Edition - Probability, Random Variables and Stochastic
R Graphics Essentials for Great Data Visualization: +200 Practical Examples You Want to Know for Data Science By 作者: Mr Alboukadel Kassambara ISBN-10 书号: 1979748101 ISBN-13 书号: 9781979748100 ...
安装$ npm install eslint-rules-variables用法var rules = require ( 'eslint-rules-variables' ) ;规则变量声明的规则。 console . dir ( rules ) ;/*{'init-declarations': 0,'no-catch-shadow': 2,...}*/例子var...
Direction parameter adjustment, including the x, y, z axis, and xy interchange four variables, ;the name of the module used for identification, and drive registered name consistent ;-----------------...
CodeWithDragos编写的Javascript变量 在Java变量上练习您的知识 练习一 请按照的说明完成练习。 尝试了解文件中正在发生的事情 在浏览器中打开文件并检查Javascript控制台 提示:您可以按照的说明打开控制台 练习二...
100个javascript练习受启发,我正在挑战自己尽可能多地使用Javascript进行编程,以刷新和扩展自己的技能。 单击颜色更改 简单动画 点击以删除 开关盒(星座) 随机卡 数组方法 单击并拖动 本地存储 实时类型(使用...
- **Magic:** Define constants for magic numbers and strings to improve code clarity. - **Ownership and Smart Pointers:** Use smart pointers like `std::unique_ptr` and `std::shared_ptr` to manage ...
We live in a data-driven world, and the goal of this text is to teach students how to access and analyze these data critically. Authors Rob Gould, Colleen Ryan, and Rebecca Wong want students to ...
gulp-less-json-variables Gulp从JSON写入较少的变量 一个简单插件。 该模块写在源文件上,从JSON配置文件中指定的变量较少。 安装 最简单的方法是将gulp gulp-less-json-variables保留为package.json的...
在“05 Coding Challenge #2 - Data Types, Variables and Arrays”这个挑战中,我们将深入理解这些核心概念。 首先,我们要了解什么是数据类型。数据类型决定了变量可以存储的数据种类。在Java中,数据类型主要...
在Java编程语言中,数据类型、变量和算术运算构成了程序的基础。让我们深入探讨这些概念。 首先,**数据类型**是编程语言中的基本构建块,它们定义了变量可以存储的数据种类。Java有两大类数据类型:**原始数据类型...