批改状态:合格
老师批语:
实例演示js常用数据类型,变量与常量的声明与赋值
let js变量声明,禁止重复赋值声明
// let:js变量声明let userName;// 第一次赋值初始化userName = 'My name';// 第二次赋值更新userName = 'Your name';// 输出 Your nameconsole.log(userName);// 直接赋值初始化let myName = 'My name';// 输出 My nameconsole.log(myName);
const js常量声明,声明与初始化同步完成,不能更改
// const: js常量声明const JS = 'Javascript';// 输出 Javascriptconsole.log(JS);
| 类型 | 引用类型 | 描述 |
|---|---|---|
| 原始类型 | 数值,字符串,布尔,undefined,null,Symbol | 原始类型都是值传递的 |
| 引用类型 | 对象,数组,函数 | 引用传递 |
// 数值类型,整数或小数let num = 1.0;// 字符串let str = 'str';// 布尔 true | falselet bool = true;// undefined 未初始化变量默认值let untitled;// null 空的对象let obj = null;// symbol 符号let s = Symbol('s');// console log/**num numberstr stringbool booleanuntitled undefinedobj objects symbol*/console.log('\nnum', typeof num, '\nstr', typeof str, '\nbool', typeof bool, '\nuntitled', typeof untitled, '\nobj', typeof obj, '\ns', typeof s);// 值传递let a = 1;let b = a;a = 2;// a= 2 b= 1,a 更新不影响 b 的值console.log('a=', a, 'b=', b);
2.2 引用类型
// 对象let user = {id: 1,'custom name': 'custom value',getId() {return this.id;},getName() {return this['custom name'];}}// console log/**id = 1'custom name' = custom valuegetId() = 1getName() = custom value*/console.log('id = ' + user.id, '\n\'custom name\' = ' + user['custom name'], '\ngetId() = ' + user.getId(), '\ngetName() = ' + user.getName());
// 数组let arr = [1, 'name', 'description'];// 输出 1 1 "name" "description" trueconsole.log(arr[0], arr[1], arr[2], Array.isArray(arr));// 赋值给 arr2,引用传递的是一个指针,内存地址相同let arr2 = arr;arr2[1] = 'modify name';// 输出 1 "modify name" "description" trueconsole.log(arr[0], arr[1], arr[2], arr instanceof Object);
// 函数function hello(a, b, c) {console.log(arguments);}// 输出 hello的类型:functionconsole.log('hello的类型:' + typeof (hello));// 输出 hello是对象:trueconsole.log('hello是对象:' + (hello instanceof Object));// 对象添加属性hello.id = 1;hello.email = 'a@b.cc';// 自带属性/**arguments: nullcaller: nulllength: 3name: "hello"*/console.log('name: ' + hello.name, '\nlength: ' + hello.length);hello(1, 2, 3, 4, 5);console.dir(hello);

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号