JavaScript 学习笔记

字符串

JavaScript 字符串是不可变的(immutable),String 类所定义的方法都不能修改字符串的内容。如果涉及修改,都是返回全新的字符串。

replace() 字符串替换,它没有在原字符串上替换,而是返回了替换后的值:

s = "hello berlin";
s = s.replace("berlin", "james");

注意:

s.replace("a", "b");

只会替换第一次出现的 a,要所有的 a 都替换为 b,应该用如下正则表达式:

s.replace(/a/g, "b");

indexOf() 进行字符串搜索,如果没有找到子串则返回-1.

String.prototype.include = function(s) {
    return this.indexOf(s) != -1;
};

var s = "Welcome to my world!";
if(s.include("world")) {
    console.log("it works!");
}

search() 进行正则表达式搜索,如果没有找到子串则返回 -1.

if(s.search("world")) {
    console.log("find it");
}
if(s.search("/Welcome/")) {
    console.log("find it");
}
if(s.search("/welcome.*world/i")) {
    console.log("find it");
}

JavaScript 中没有 startsWith()endsWith() 这样的实用函数,可以自己添加:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function(prefix) {
        return this.slice(0, prefix.length) === prefix;
    };
} 

if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

注意 startsWith() 的实现没有使用 indexOf(),因为 indexOf() 会扫描整个字符串。

trim() 删除字符串前后空格。

split() 将字符串转为数组,可以用正则表达式,如:

var s = "  623205  EA911785091CN  AU  Alice Hertson  ";
console.log(s.trim().split(/\s+/));

第 10 章 模块

ES6 模块导入

import 可以导入模块,有以下多种导入形式:

import { mean, stddev } from "./stats.js"
import * as stats from "./stats.js"

import() 动态导入模块:

import('./stats.js').then(stats => {
    let average = stats.mean(data);
});

注意 import() 是操作符不是函数。

第 15 章 客户端 JavaScript

客户端 JavaScript 的输入来源:

  1. 事件
  2. 文本内容,通过 DOM API 访问
  3. 客户端环境,如 document, navigator, screen, window 等全局属性:
    1. document.cookie, document.URL
    2. navigator.userAgent, navigator.language, navigator.hardwareConcurrency
    3. screen.width, screen.height
    4. window.innerWidth

DOM(Document Object Module)文档对象模型。每个 HTML 标签都有一个对应的 Element 对象;所有文本都与之对应的 Text 对象;注释对应 Comment 对象。

操作 DOM

选择 DOM 元素:

  1. querySelector() 返回第一个匹配元素
  2. querySelectorAll() 返回所有匹配元素

旧的 DOM 元素选择方法已不再推荐使用,以下是新旧写法的对比:

document.getElementsByTagName('h2');
document.querySelectorAll('h2');

document.getElementById('toc');
document.querySelector('#toc');

document.getElementsByClassName('highlight');
document.querySelectorAll('.highlight');

document.getElementsByName('sword');
document.querySelectorAll('*[name=sword]');

Element.className 获取或设置 class 属性:

let c = e.className;
e.className = c;

将一个元素的 class 属性复制给另一个元素的其他方法:

e.setAttribute('class', t.getAttribute('class'));

Element.classList 以集合的形式操作 class 属性,它包含以下方法:

  • add()
  • remove()
  • replace()
  • toggle(token) - token 存在则删除,token 不存在则添加

classList 类继承自 DOMTokenList,后者还包含以下属性和方法:

  • length
  • value - 返回字符串
  • item(i) - 输入 index 返回相应的值,若超过 length 则返回 undefined
  • contains(token) - 返回 true, false
  • supports(s)
  • entries()
  • forEach()
  • keys()
  • values()

示例:

e.classList.add('text-muted', 'm-3');
e.classList.remove('text-muted', 'm-3');
e.classList.item(0);
e.classList.contains('sticky');
e.classList.toggle('hide');