您需要了解哪些 JavaScript 知识才能更有效地编写单页应用程序:指南摘要 JavaScript 基础知识 DOM 操作 箭头函数 数组方法 异步 JavaScript 使用 Fetch 向 API 发出请求 ES 模块 使用 NPM 进行包管理 结论

2025-06-07

你需要了解哪些 JavaScript 知识才能更有效地编写单页应用程序:指南

概括

JavaScript 基础

DOM 操作

箭头函数

数组方法

异步 JavaScript

使用 Fetch 向 API 发出请求

ES 模块

使用 NPM 进行包管理

结论

如果您有兴趣了解 JavaScript 的哪些方面对于 React 或 Vue 等框架很重要,那么本文适合您。

我将介绍在使用 React 或 Vue 进行开发时所使用的 JavaScript 方面。

概括

  • JavaScript 基础
  • 基本 DOM 操作
  • 箭头函数
  • 数组方法
  • 异步 JavaScript
  • 使用 Fetch 向 API 发出请求
  • ES 模块
  • 新公共管理

在我们开始之前,我只想说,使用 React 或 Vue 并不一定需要了解所有这些概念。

当我第一次开始使用 React 和 Vue 时,我确实并不了解一切。

理解这些概念以及 JavaScript 在浏览器中的工作方式非常重要,这将为您学习 React 和 Vue 奠定良好的基础。

JavaScript 基础

与所有事物一样,JavaScript 的基础知识非常重要。

变量

在 JavaScript 中,您可以使用关键字 const、var 和 let 创建变量。

const 用于声明常量 - 这些变量的值不会随时间而改变。

const daysOfTheWeek = 7;
Enter fullscreen mode Exit fullscreen mode

let 和 var 的使用方法相同,但关键字放在变量名之前:

let firstName = "Jane";

var lastName = "Doe";
Enter fullscreen mode Exit fullscreen mode

当我们拥有的值会随着时间而改变的变量时,通常会使用这些。

您可能会问自己,为什么有两个关键字具有相同的功能。

有一点小差别。

function varExample ()
{
    var name = "Jane";

    if(name === "Jane")
    {
        var name = "Doe"; //    the same variable as above
        console.log(name) //    will return "Doe"
    }

    console.log(name); //    will also return "Doe"
}

function letExample ()
{
    let name = "Jane";

    if(name === "Jane")
    {
        let name = "Doe"; //    new variable is created
        console.log(name) //    will return "Doe"
    }

    console.log(name); //    will also return "Jane"
}
Enter fullscreen mode Exit fullscreen mode

使用 var 创建的变量会被更新,无论它在函数中的哪个位置被调用。

使用 let 创建的变量不会更新,因为该变量的值特定于它所创建的块。

现在我们知道了如何在 JavaScript 中创建变量,我们可以继续查看 JavaScript 中的数据类型。

内置数据类型

在编写 JavaScript 时,您不会声明正在创建的变量的类型。

然而,了解 JavaScript 的狂野西部中存在哪些数据类型可能会有所帮助:

  • 不明确的
  • 数字
  • 布尔值
  • 细绳
  • BigInt
  • 象征

有关 JavaScript 类型的更多信息,您可以查看Mozilla的精彩文档

字符串操作

能够操作字符串是构建应用程序时经常需要的另一项任务。

将两个字符串相加

let firstName = "Jane";
let lastName = "Doe";

//joining them using a '+'
let fullNameOne = firstName + " " + lastName;

console.log(fullNameOne);

//or using template string by using backticks(``)
let fullNameTwo = `${firstName} ${lastName}`;

console.log(fullNameTwo);

//both will result in "Jane Doe"
Enter fullscreen mode Exit fullscreen mode

我们可以直接使用我们创建的变量来构建将用作用户界面一部分的最终字符串。

字符串还具有我们可以访问的属性,例如长度:

let firstName = "Jane"

let firstNameLength = firstName.length

//will output "4"
console.log(firstNameLength);
Enter fullscreen mode Exit fullscreen mode

我们还可以使用内置方法将字符串转换为大写和小写:

let firstName = "Jane";

let upperCaseName = firstName.toUpperCase();
let lowerCaseName = firstName.toLowerCase();

console.log(upperCaseName);//Output: "JANE"
console.log(lowerCaseName);//Output: "jane"
Enter fullscreen mode Exit fullscreen mode

这些只是使用内置 JavaScript 方法可以执行的操作的一小部分。

DOM 操作

JavaScript 无疑是一门强大的 Web 语言。它允许我们直接修改浏览器中显示的内容。使用 JavaScript,我们可以响应用户输入。

这种反应性是一个需要理解的重要概念,尤其是当我们开始使用 React 或 Vue 时。

从网页中选择元素

使用 JavaScript 操作 DOM 的第一步是了解如何选择要操作的元素。

您可能会看到的较旧方法是这样的:

//this will store all elements that have a class of "title" within our heading variable
let heading = document.getElementByClassName("title");

//this will store the element with the Id "submit" within our button variable
let button = document.getElementById("submit");
Enter fullscreen mode Exit fullscreen mode

一种较新的方法是使用 querySelector():

//this will store the *first* element that has a class of "title" within our heading variable
let heading = document.querySelector(".title");

//this will store the element with the Id "submit" within our button variable
let button = document.querySelector("#submit");

//this will store all of the elements that have a class of "title" within our heading variable as an array
let heading = document.querySelectorAll(".title");
Enter fullscreen mode Exit fullscreen mode

创建 DOM 元素

JavaScript 的另一个重要特性是能够创建在浏览器中呈现的元素。

当您从 API 检索数据并希望将其显示在列表中时很有用。

//here we have our heading
const heading = document.querySelector('.heading');

//now let us add our subheading
const subheading = document.createElement('h5');
subheading.textContent = "I am a subheading";

//we can now add this subheading to the heading element
heading.appendChild(subheading);
Enter fullscreen mode Exit fullscreen mode

处理用户输入

这很可能是编写 React 和 Vue 应用时最常见的任务之一。因此,了解其工作原理也至关重要。

假设我们有一个表单,我们想要获取用户在用户名字段中输入的内容。

该表单有两个部分:一个输入字段和一个按钮:

<input type="text" class="username">
<button class="submit-btn" onClick="submitData()">
  Submit
</button>
Enter fullscreen mode Exit fullscreen mode

使用 onClick 我们可以定义单击按钮时需要发生什么:

const submitData = () => {
        let username = document.querySelector(".username").value;

  console.log(username);  //will print our the text entered in the input field to the console
}
Enter fullscreen mode Exit fullscreen mode

我们还可以进行调整,以便在每次向输入中添加新字符时验证用户输入:

<input type="text" class="username" onkeyup="logInput()">
<button class="submit-btn" onClick="submitData()">
  Submit
</button>
Enter fullscreen mode Exit fullscreen mode
const logInput = () => {
    let username = document.querySelector(".username").value;

  console.log(username); 
 //will produce if typed slow enough:
 // "J"
 // "Ja"
 // "Jan"
 // "Jane"
}
Enter fullscreen mode Exit fullscreen mode

根据用户输入可以触发许多不同的事件。

使用 JavaScript 动态设置元素样式

JavaScript 允许我们动态更新 UI 的样式,从而允许我们根据用户的输入向他们提供反馈。

当我们以表单形式验证电子邮件时非常方便:

<input type="text" class="user-email" onkeyup="validateInput()">
Enter fullscreen mode Exit fullscreen mode

我们正在验证电子邮件中的每个字符,向用户提供反馈并让他们知道他们的输入是否有效。

这样就避免了他们提交数据后,在验证检查失败后必须进行更正的麻烦。

const validateInput = () => {
    //select the input element
    let emailInputElement = document.querySelector(".user-email");

  //get the value of the input field
  let userEmail = emailInputElement.value;

  //decide if the e-mail is valid or not
  if(!userEmail.includes("@"))
  {
    //here we are adding the red border of the e-mail is valid
    emailInputElement.classList.add("invalid-input");

    //and removing it, if the e-mail becomes invalid again
    emailInputElement.classList.remove("valid-input");
  } else {
        //here we add the green border if it is valid
        emailInputElement.classList.add("valid-input");

      //and remove the red border
      emailInputElement.classList.remove("invalid-input");
  }
}
Enter fullscreen mode Exit fullscreen mode

通过这些操作,我绝对会鼓励您尝试构建一些小项目,专注于使用 JavaScript 在您的应用程序中构建一些反应性。

箭头函数

在我展示的几个例子中,你可能已经看到过这个“=>”。这些被称为箭头函数,可以简化更传统的函数声明:

//traditional JavaScript function
function generateFullName(firstName, lastName){
    return `${firstName} ${lastName}`;
}

//will return "Jane Doe"
console.log(generateFullName("Jane", "Doe"));

//arrow function with name
const generateFullNameArrow = (firstName, lastName) => `${firstName} ${lastName}`

//arrow function returning "Jane Doe"
console.log(generateFullNameArrow("Jane", "Doe"));
Enter fullscreen mode Exit fullscreen mode

数组方法

在处理从 API 检索的数据时,这些可能是 JavaScript 最广泛使用的方面之一。

在 JavaScript 中可以使用以下语法创建数组:

let nameArray = ["Jane", "John", "Sarah", "Mike"];
Enter fullscreen mode Exit fullscreen mode

很简单吧?

我们将数据存储在一个变量中,这就是为什么我们在开头需要一个 let。

数组有不同的方法允许我们交互和操作其中的数据。

仔细检查每一项

要遍历数组中的每个项目,我们可以使用 forEach 方法:

nameArray.forEach(name => console.log(name));

//    Output: "Jane"
//    Output: "John"
//    Output: "Sarah"
//    Output: "Mike"
Enter fullscreen mode Exit fullscreen mode

这与 for 循环完全相同:

for(let i = 0; i < nameArray.length; i++)
{
    console.log(nameArray[i]);
}

Enter fullscreen mode Exit fullscreen mode

forEach 方法允许我们编写更少的代码,但是实现这一点并没有正确或错误的方法。

console.log(nameArray[i]);就是我们如何访问数组中的特定元素。

我们需要知道数组中的元素的索引。

对于我们的 nameArray 数组,我们有以下内容:

//index             0       1       2        3    
let nameArray = ["Jane", "John", "Sarah", "Mike"];

//accessing the name Sarah
console.log(nameArray[2]);
Enter fullscreen mode Exit fullscreen mode

在 JavaScript 中,索引从 0 开始向上。

过滤项目

JavaScript 还具有内置的 filter() 函数,允许我们获取原始数组并创建一个包含满足特定条件的项目的新数组。

//will give us a new array with names that have 4 letters or less
let namesThatHaveFourLetters = nameArray.filter(name => name.length <= 4);

//output: ["Jane", "John", "Mike"]
console.log(namesThatHaveFourLetters);
Enter fullscreen mode Exit fullscreen mode

这将仅包括包含 4 个或更少字符的名称。

将更改应用于所有项目

我推荐使用的另一种好方法是 map() 方法。

它允许我们对数组的每个项目应用更改:

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

let doubledNumbersArray = randomNumbersArray.map(number => number * 2);

console.log(doubledNumbersArray);

//output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

从数组中添加和删除项目

出现的另一个任务是从数组中添加和删除项目:

//add item to the end of an array
let nameArray.push("Amy");

//add item to the start of an array
let nameArray.unshift("Tom");

//remove item from the end of an array
let nameArray.pop(); //removes "Amy" from array

//remove item from the start of an array
let nameArray.shift(); // removes "Tom" from array
Enter fullscreen mode Exit fullscreen mode

我再次建议您查看Mozilla 的文档,其中有 JavaScript 中数组功能的更完整列表。

异步 JavaScript

这是使用基于 JavaScript 的技术时的一个关键概念。

同步应用程序是我们通常熟悉的应用程序——一行代码接一行地执行,并且没有两个任务同时执行。

当你正在执行一段密集的代码,并等待其完成后才能继续执行下一个任务时,这可能会成为一个问题。如果在浏览器中发生这种情况,你很可能会看不到任何响应,并认为浏览器卡住了。

您会发现,许多与从服务器获取某种资源相关的任务现在都具有异步运行的代码。

使用 setTimeout 我们可以轻松展示 JavaScript 如何让我们异步运行代码:

setTimeout( () => {
    console.log("First console log");
}, 2000);

console.log("Second console log");

//Output:
//"Second console log"
//"First console log"
Enter fullscreen mode Exit fullscreen mode

这是使用回调仅在 2 秒后运行函数内部的任何内容。

这意味着当函数等待解析时,JavaScript 会进入下一行。

有一种使用 Promises 编写这些类型的异步任务的更新、更现代的方法:

fetch("api/for/some/resource")
//Promises have a characteristic .then()
  .then( response => {
    console.log(response.data);
//it is common to use .catch() to log any errors
}).then( json => {
    console.log(json);
}).catch( error => {
    console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

.then() 中的代码仅在 fetch() 返回结果时执行。如果 fetch() 返回错误,则会调用 .catch() 代码块。

使用 async/await 可以实现第三级异步 JavaScript:

//the async keyword comes before the function you want to use await in
const data = async () => {
    //get the resource returned by the api
    const resource = await fetch("api/for/some/resource")
    //convert the returned data to json
    const posts = await resource.json();
    //make it available
    return posts;
}
Enter fullscreen mode Exit fullscreen mode

正如您所看到的,这确实使您的代码更具可读性和更清晰易懂。

使用 Fetch 向 API 发出请求

在项目前端工作时,主要任务之一是从后端发送和接收数据。

fetch API 为我们提供了一种非常方便的方法来做到这一点:

const getUserData = async () => {
    const response = await fetch('api/user/resource', {
        method: 'GET' //'POST', 'PUT', 'PATCH', 'DELETE'
    });

    const data = await response.json();

    return data;
}
Enter fullscreen mode Exit fullscreen mode

如果我们想将数据发布到服务器,我们只需使用“POST”方法:

const formData = { firstName: "Jane" };

const postUserData = async () => {
    const response = await fetch('api/user/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=UTF-8'
        },
        body: JSON.stringify(formData),
    });

    const data = await response.json();

    return data;
}
Enter fullscreen mode Exit fullscreen mode

您可以使用的所有其他 Http 动词都可以执行相同的操作。

这几乎构成了使用 Vue 或 React 构建单页应用程序的支柱。

Mozilla在记录如何使用 Fetch API 方面再次做得非常出色。

ES 模块

模块允许我们在一个文件中编写逻辑,导出我们想要的逻辑并将其导入我们需要的文件中。

在我们有模块之前这是可能的:

const library = require('library-name);
Enter fullscreen mode Exit fullscreen mode

模块语法如下:

import library from 'library-name';
Enter fullscreen mode Exit fullscreen mode

为了能够导入任何库或逻辑,我们需要首先使其可导入。这可以通过 export 关键字完成。

//roundNumber.js
export default decimal => Math.round(decimal);
Enter fullscreen mode Exit fullscreen mode

我们现在可以在我们的 app.js 文件中使用它:

//app.js
import roundNumber from './roundNumber.js';

let decimal = 3,2;

let roundedDecimal = roundNumber(decimal);
Enter fullscreen mode Exit fullscreen mode

在 Vue 或 React 项目中,您肯定会从不同的第三方工具导入功能,并导出自己的逻辑以供整个应用程序使用。

使用 NPM 进行包管理

当您第一次以开发人员的身份开始新工作时,您很可能会从事现有项目。

这意味着您需要设置并安装项目的所有依赖项。

幸运的是,我们有一个叫做 npm 的东西,我们可以用它轻松安装项目的 package.json 文件中定义的所有依赖项。

要安装文件中定义的所有包,只需运行npm install

您将看到已创建的 node_modules 目录,您猜对了,所有模块/依赖项都已安装,可以导入。

您还可以使用将包添加到项目中npm install <package-name>

此外,我们可以定义哪些模块将在生产中使用(使用npm install <package-name> --save)以及哪些是纯开发依赖项(使用npm install <package-name> --save-dev)。

测试库通常在开发期间使用,但在生产期间不需要。

最后,我们还可以在 package.json 中定义命令,然后使用 npm 运行这些命令:

//package.json
{
    "scripts": {
        "dev": "vue-cli-service serve",
    }
}
Enter fullscreen mode Exit fullscreen mode

然后我们可以通过运行使用 npm 引用它npm run dev,在这种情况下将启动我们的 Vue 应用程序的开发服务器。

结论

我希望这个简短的概述能让你了解开始使用 React 或 Vue 时需要了解的内容。

就像我在开始时写的那样,没有必要了解所有这些,但熟悉这些概念确实有助于并加快你的进度。

如果我遗漏了任何与学习相关的内容,请在评论中告诉我。

文章来源:https://dev.to/rjzauner/what-javascript-do-you-need-to-know-to-write-single-page-applications-more-efficiently-a-guide-489g
PREV
如何使用 useEffect 复制 React 组件的生命周期
NEXT
创建一个可以动态处理多个音频源的音频可视化器 - 全部使用 Vanilla JS!