Bootstrap

Javascript基础语法详解

  • 面向对象的语言.
  • 脚本语言,不需要编译,浏览器解释即可运行 .
  • 用于控制网页的行为.
  • 浏览器的source可以打断点调试, console输入代码可以执行
use strict指令:

在“严格模式”下运行js代码, 防止意外创建全局变量等, 提高代码安全性和执行效率.

使用:
  • 全局严格模式:在脚本的开头添加 "use strict".
  • 函数级严格模式: 在函数的开头添加 "use strict"
    function myFunction() {
        "use strict";
        // 仅该函数内部运行在严格模式下
    }
    
js的引入
1. 内部脚本
  • js可以放在任意位置,一般放在body标签底部.
<body>
    <h1>Hello, World!</h1>
    <script>
        console.log("Hello from inline script!");
    </script>
</body>
2. 外部脚本
<head>
    <script src="script.js"></script>
</head>

基础语法
  • js区分大小写,语句末尾的分号可有可无
  • 注释和java一样
输出语句

window.alert(): 弹出警告框, window.可省略.

document.write(): 显示在页面上.

console.log() : 打印在控制台.

基本数据类型
  • 原始数据类型是不可变的,存储在栈内存中,按值比较.
  • Number:数字
  • String:字符串,用单引号、双引号包裹
  • Boolean:布尔值
  • Undefined:变量未赋值.
  • Null:表示“无”或“空值”,类型是 object
引用数据类型
  • 引用数据类型是可变的,存储在堆内存中,按引用比较

  • Object:表示对象,可以存储键值对

    let person = {
        name: 'Alice',
        age: 30
    };
    
  • Array:数组

    let numbers = [1, 2, 3, 4, 5];
    
  • Function:函数也是对象

    function greet() {
        return 'Hello!';
    }
    
  • Date:日期和时间

    let now = new Date();
    
类型检查

typeof :检查数据类型。

console.log(typeof num1); // "number"
console.log(typeof str1); // "string"
console.log(typeof isActive); // "boolean"
console.log(typeof notAssigned); // "undefined"
console.log(typeof emptyValue); // "object"
console.log(typeof person); // "object"
console.log(typeof numbers); // "object"
console.log(typeof greet); // "function"
字符串

length : 字符串长度

charAt() : 返回指定位置的字符
indexOf() : 查找子字符串首次出现的位置
trim() : 去除字符串两边的空格
substring() : 截取字符串

变量
1. var
  • var定义的变量可以被覆盖.
  • 具有函数作用域, 在函数内声明的var变量在函数内有效:
function testVar() {
    if (true) {
        var x = 10; // 函数作用域
    }
    console.log(x); // 输出: 10
}
testVar();

//在函数外不能访问:
<script>  
    function testVar() {  
        if (true) {  
            var x = 10; // 函数作用域  
        }   
    }  
    alert(x);  
</script>
  • 不受块级作用域{}影响,即使声明在块内,块外也可以访问。
{
    var x = 10;
}
console.log(x); // 输出: 10

2. let
  • 具有块级作用域:变量只在声明的 {} 内有效,超出作用域不能访问
<script>  
    {  
        let a = 1;  
    }  
    alert(a);  //不会弹出警告框
</script>
  • 不能重复定义
{  
    let a = 1;  
    let a="s";  //报错
}
3. const
  • 作用域:和let一样,也不能重复定义

    {
      const d = 20;
      console.log(d); // 输出 20
    }
    console.log(d); // 报错: Uncaught ReferenceError: d is not defined
    
  • const 声明的变量必须初始化.

  • const修饰的原始数据类型不能重新赋值

  • const修饰的引用数据类型如对象,数组的内容可以修改,引用(地址)不能修改。

    const f = 30;
    f = 40; // 报错: TypeError: Assignment to constant variable.
    
    const arr = [1, 2, 3];
    arr.push(4); // 合法操作
    console.log(arr); // 输出 [1, 2, 3, 4]
    
显式类型转换
转换为字符串
console.log(String(123)); // 输出 "123"
console.log((123).toString()); // 输出 "123"
console.log(String(true)); // 输出 "true"
console.log(String(null)); // 输出 "null"
转换为数字
console.log(Number("123")); // 输出 123
console.log(Number("")); // 输出 0
console.log(Number("123abc")); // 输出 NaN
console.log(parseInt("123.45")); // 输出 123
console.log(parseFloat("123.45")); // 输出 123.45
转换为布尔值
  • 0NaNfalse;
  • 空字符串是false;
  • NullUndefinedfalse;
console.log(Boolean(1)); // 输出 true
console.log(Boolean(0)); // 输出 false
console.log(Boolean("")); // 输出 false
console.log(Boolean("hello")); // 输出 true

不要使用==比较,使用===等号,因为===不仅比较值,还会比较类型是否相等.

循环
for...in循环:
  • 可用于遍历对象,数组的属性,不能遍历字符串、SetMap.
  • 用于数组时,遍历的是数组的索引,不是数组的值。
let obj = { name: "Alice", age: 25, city: "NY" };
for (const key in obj) {
  console.log(key, obj[key]);
}
// 输出:
// name Alice
// age 25
// city NY

for...of循环:
  • 直接遍历值,可用于数组、字符串、SetMap 等,不能遍历对象
let arr = ["a", "b", "c"];

for (const value of arr) {
  console.log(value); // 输出 "a", "b", "c"(值)
}

forEach() 循环

用于遍历数组.

语法:

array.forEach(function(currentValue, index, array) {

});

//currentValue(必需):当前正在处理的元素。
//index(可选):当前元素的索引
//array(可选):调用 forEach() 的原数组

示例:

let fruits = ["apple", "banana", "orange"];

fruits.forEach(function(fruit, index) {
  console.log(index + ": " + fruit);
});

//输出:
/*0: apple
1: banana
2: orange*/

let numbers = [1, 2, 3, 4];

numbers.forEach(num => console.log(num * 2));

//输出:2 4 6 8

注意:

forEach() 无法中途退出循环(break无效),return 也不会停止循环:

let arr = [1, 2, 3, 4, 5];

arr.forEach(num => {
  if (num === 3) return; // 这里的 return 只会跳过当前迭代,不会终止循环
  console.log(num);
});

forEach() 不能直接修改原数组:

let arr = [1, 2, 3];

arr.forEach(num => num = num * 2); // 这样不会改变数组
console.log(arr);  // [1, 2, 3]

forEach() 不会跳过 undefined.

;