Javascript-variables变量


<button id="button_A">Press me</button>
<h3 id="heading_A"></h3>

const buttonA = document.querySelector('#button_A');
const headingA = document.querySelector('#heading_A');
buttonA.onclick = function() {
  let name = prompt('What is your name?');
  alert('Hello' + name + ', nice to see you!');
  headingA.textContent = 'Welcome ' + name;
}

如果没有变量, 我们就需要多次的问用户的姓名。
Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

Note: We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.


定义变量有两个关键字, var 和 let
为什么我们需要2个?
这是个历史问题, 刚开始只有var, its design can sometimes be confusing or downright annoying

let是后来出现的解决var带来的一些困惑,他和var有些不同。
if you really want to read about them now, feel free to check out our let reference page。 


当你写多行代码的时候,var 声明变量,写在后面也可以运行。

myName = 'Chris';

function logName() {
  console.log(myName);
}

logName();

var myName;


hoisting 不再被let使用,

var 定义变量,可定义多次,但是let不行;
多次的定义变量会让人困惑。

变量命名:0-9 a-z A-Z underscore character

不要用 underscore开头,这是 this is used in certain JavaScript constructs to mean specific things, so may get confusing.
不用数字开头
lower camel case

你不需要声明变量的类型。

When you give a variable a string value, you need to wrap it in single or double quote marks;

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc).

let myNumber = '500'; // oops, this is still a string
typeof myNumber;
myNumber = 500; // much better — now this is a number
typeof myNumber;

常量

有很多原因,你可能希望一个value声明后不能再改变,第三方的脚本调用,代码好理解。
In the early days of JavaScript, constants didn't exist. 
In modern JavaScript, we have the keyword const, which lets us store values that can never be changed:

const daysInWeek = 7;
const hoursInDay = 24;



阅读量: 557
发布于:
修改于: