Master the front-end tool: Analysis and practical use of high-level JavaScript page rendering methods

introduction

In front-end development, the speed and quality of page rendering are important criteria for measuring a developer's level. Among the many front-end technologies, JavaScript ranks first with its powerful page rendering capabilities. This article will delve into the application of JavaScript in page rendering and demonstrate its high-level methods through examples, aiming to help readers better master front-end technology.

The importance of JavaScript in page rendering

JavaScript has been a powerful programming language since its creation, allowing developers to manipulate the browser's DOM (Document Object Model) to change the content and style of web pages. Through JavaScript, we can implement dynamic content, interactive effects, single-page applications (SPA), etc.

With the development of front-end technology, the role of JavaScript is also expanding. Now, it is not only a tool for page rendering, but also a means of building complex front-end applications. Therefore, mastering the high-level methods of JavaScript page rendering is crucial for front-end developers.

High-order method analysis

Higher-order functions are an important concept in JavaScript. They refer to functions that accept functions as parameters or return functions. In page rendering, higher-order functions are also widely used.

map(), reduce() and filter()

These three functions are commonly used higher-order functions in arrays. They both accept a function as argument and return a new array.

  • map(): Used to convert each element in the array into a new element through a function and return a new array.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2); // [2, 4, 6, 8, 10]
  • filter(): Used to filter out elements in an array that meet specific conditions and return a new array.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0); // [2, 4]
  • reduce(): Used to accumulate elements in an array through a function and return a single result.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, number) => accumulator + number, 0); // 15

sortBy()

sortBy()Function is used to sort the elements in an array according to a given attribute. It accepts a function as parameter, which defines the collation.

const people = [
  {
    
     name: 'Alice', age: 25 },
  {
    
     name: 'Bob', age: 20 },
  {
    
     name: 'Charlie', age: 30 }
];
const sortedPeople = people.sortBy(person => person.age); // [{ name: 'Bob', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 }]

find()、findIndex()和includes()

These three functions are used to find elements in an array.

  • find(): Returns the first element that meets certain conditions.
  • findIndex(): Returns the index of the first element that meets a specific condition.
  • includes(): Determine whether an array contains a specific value.
const numbers = [1, 2, 3, 4, 5];
const foundNumber = numbers.find(number => number > 3); // 4
const foundIndex = numbers.findIndex(number => number > 3); // 3
const containsFour = numbers.includes(4); // true

Practical case of high-order methods: dynamic table sorting and filtering

Let us demonstrate the application of higher-order methods through a case of dynamic table sorting and filtering. Suppose we have a table, each row represents a user, and each column represents the user's attributes (such as name, age, etc.). Users can sort and filter by different attributes.

data preparation

First, we need to prepare some user data. Here we use an array containing multiple user objects to represent the data source. Each user object contains attributes such as name, age, etc.

const users = [
  {
    
     name: 'Alice', age: 25 },
  {
    
     name: 'Bob', age: 20 },
  {
    
     name: 'Charlie', age: 30 },
  // ...更多用户数据...
];

Implementation of header sorting and filtering functions

Next, we use higher-order functions to implement the sorting and filtering functions of the table header. Here we use the sortBy()and filter()function to achieve this. When the user clicks on the table header, we sort the user data according to the attributes corresponding to the table header; when the user selects the filter conditions, we filter the user data according to the filter conditions. Here is the JavaScript code that implements this functionality:

// 获取表格元素
const table = document.getElementById('users-table');

// 获取表头元素
const headers = table.getElementsByTagName('th');

// 为每个表头添加点击事件
for (let header of headers) {
    
    
  header.addEventListener('click', function () {
    
    
    const property = header.dataset.property; // 获取表头对应的属性

    // 对用户数据进行排序
    users.sort((a, b) => {
    
    
      if (a[property] < b[property]) {
    
    
        return -1;
      } else if (a[property] > b[property]) {
    
    
        return 1;
      } else {
    
    
        return 0;
      }
    });

    // 重新渲染表格
    renderTable(users);
  });
}

// 筛选功能(根据年龄筛选)
const ageSelect = document.getElementById('age-select');
ageSelect.addEventListener('change', function () {
    
    
  const age = ageSelect.value; // 获取筛选条件(年龄)

  // 对用户数据进行筛选
  users = users.filter(user => user.age === age);

  // 重新渲染表格
  renderTable(users);
});

// 渲染表格的函数
function renderTable(users) {
    
    
  const tbody = document.getElementById('users-tbody');
  tbody.innerHTML = ''; // 清空原有的表格数据

  // 遍历用户数据,为每个用户创建一个表格行(tr)
  users.forEach(user => {
    
    
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${
      
      user.name}</td>
      <td>${
      
      user.age}</td>
    `;
    tbody.appendChild(row); // 将表格行添加到表格中
  });
}

In the above code, we first obtain the table element and header element containing user data, and add a click event to each header. When the user clicks on the header, we sort the user data according to the attributes corresponding to the header, and use sort()methods to sort in ascending or descending order. Then, we re-render the table and display the sorted user data in the table. Additionally, we implemented a filtering feature that allows users to filter user data based on age. When the user selects an age, we filter the user data based on the selected age and re-render the table to display the filtered user data in the table. Finally, we define a renderTable()function that re-renders the table based on the current user data. In the function, we cleared the original table data and used forEach()the method to traverse the user data, create a table row (tr) for each user, and add the row to the tbody element of the table.


This time the summary of the article is left to the smart readers.

Guess you like

Origin blog.csdn.net/weixin_46254812/article/details/132632384