<返回更多

JS:定义变量的var、let有何操作?

2020-07-09    
加入收藏

最近话不多,直接看代码和结果好伐?

一、var

定义:

//一般情况
var word = "Hello World";
console.log(word);
//输出:Hello World

//变量提升?
console.log(word);
var word = "Hello World";
//输出:undefined

//变量提升!
word = "哈哈哈";
console.log(word);
var word = "Hello World";
//输出:哈哈哈

//所谓的全局变量,已经在window对象上了
var word = "Hello World";
console.log(window.word);
//输出:Hello World

//不写var
word = "Hello World";
console.log(word);
console.log(window.word);
//输出:
//Hello World
//Hello World

函数:

//一般情况
var word = "Hello World";
function PLAYFULHD() {
  console.log(word);
}
PLAYFULHD();
//输出:Hello World

//变量提升?
PLAYFULHD();
var word = "Hello World";
function PLAYFULHD() {
  console.log(word);
}
//输出:undefined

//变量提升?
PLAYFULHD();
function PLAYFULHD() {
  console.log(word);
}
var word = "Hello World";
//输出:undefined

//变量提升!
word = "嘿嘿嘿";
PLAYFULHD();
function PLAYFULHD() {
  console.log(word);
}
var word = "Hello World";
//输出:嘿嘿嘿

//不写var
word = "Hello World";
function PLAYFULHD() {
    var word = "嘿嘿嘿";
    console.log(word);
}
PLAYFULHD();
console.log(word);
//输出:
//嘿嘿嘿
//Hello World

重复定义:

//重复定义1
var word = "Hello World";
console.log(word);
var word = "哦吼吼";
console.log(word);
//输出:
//Hello World
//哦吼吼

//重复定义2
var word = "Hello World";
console.log(word);
function PLAYFULHD() {
    var word = "哦吼吼";
    //let word = "哦吼吼"; //效果一样
    console.log(word);
}
PLAYFULHD();
console.log(word);
//输出:
//Hello World
//哦吼吼
//Hello World

总结:

//正常情况
arr = ["HHHH"];
console.log(arr);
var arr = ["哈哈哈", "嘿嘿嘿", "哦吼吼"];
//输出:["HHHH"]

//直接报错
arr[0] = "HHHH";
console.log(arr);
var arr = ["哈哈哈", "嘿嘿嘿", "哦吼吼"];
//输出:Uncaught TypeError: Cannot set property '0' of undefined

二、let

必须先定义,再使用;其它情况同var

//直接报错
word = "哈哈哈";
console.log(word);
let word = "Hello World";
//输出:Uncaught ReferenceError: Cannot access 'word' before initialization

//不绑定到window
let word = "Hello World";
console.log(word);
console.log(window.word);
//Hello World
//undefined

三、总结

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>