I have been learning JS table sorting recently, but I didn’t expect that the inconspicuous table sorting actually implies many JS knowledge points. Record this learning process here. Hope it helps everyone too.
Complete table sorting involves the following knowledge points:
call method uses
-
sort method in-depth
Data Binding
DOM Mapping
Function.prototype. Any function we define can be considered as an instance of the
Function class. Then you can find the prototype of the class through the
__proto__ attribute of the instance. Any function can call methods such as
call and
apply.
var obj = { name : 'JS' } function testCall () { console.log(this); } testCall.call( obj ); // {name: "JS"}First function
testCall finds the call method to execute through the prototype chain search mechanism. The call method calls the call method during the execution process. This in the instance is changed to the first parameter of call, and then the instance function of the call method is called and executed.
function fn1() { console.log(1); console.log(this); } function fn2() { console.log(2); console.log(this); } fn1.call(fn2); //this -> fn2 fn1.call.call(fn2); //这里的call是改变function.__proto__.call的call方法中的this,相当于执行参数When the call method is executed, the first parameter of the call method is used to change this, and starting from the second parameter is passed to The parameters of the function calling call. In non-strict mode, if no parameters are passed to the call method, or null or undefined is passed, this will point to
window.
sum.call(); //window sum.call(null); //window sum.call(undefined); //windowThe execution of call in strict mode is different from that in non-strict mode:
sum.call(); //undefined sum.call(null); //null sum.call(undefined); //undefinedThe following uses the call method to implement a method of converting an array-like array into an array:
function listToArray (likeAry) { var ary = []; try { ary = Array.prototype.slice.call(likeAry); } catch (e) { for (var i = 0; i and call Similar methods include the apply and bind methods, which are briefly summarized here. <p></p>The apply method has the same function as the call method, except that the form of passing parameters is different. apply wraps the parameters of the function in an array: <p></p><pre class="brush:php;toolbar:false">function sum(num1, num2) { console.log(num2 + num1); console.log(this); } sum.apply(null,[100,200]);The bind method is also used to change this key Literal, but it only changes the point of this and does not immediately execute the function that calls this.
function sum(num1, num2) { console.log(num2 + num1); console.log(this); } var obj = {name : 'zx'} var temp = sum.bind(obj); //temp已经是被改变了this的函数 temp(100,200); //当我们需要的时候才执行 //或者像这样处理 var temp = sum.bind(null, 100, 200); temp();The bind method embodies the preprocessing idea in js. 2. In-depth sortingWe know that the
sort method of an array can only sort arrays within 10. If there are numbers greater than 10 in the array that needs to be sorted, we need to pass the callback function to the
sort method. The common one is like this:
ary.sort(function (a,b) { return a - b; });This way, the array can be sorted in ascending order. . So what is the principle behind this sorting? For the two parameters passed in:
a represents the current item in the found array, and
b represents the item after the current item.
return a -b
: If a is greater than b, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is ascending order
return b -a
: If b is greater than a, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is descending order
var persons = [{ name:'dawei', age:55 },{ name:'ahung', age:3 },{ name:'maomi', age:2 },{ name:'heizi', age:78 },{ name:'afu', age:32 }];It’s actually very simple:
ary.sort(function(a,b){ return a.age - b.age; });If you sort by name, the
localeCompare() method of the string is involved:
ary.sort(function(a,b){ return a.name.localeCompare(b.name); });
name.localeCompare()This method will compare the letters of the two strings. If the first letter of the previous string appears in a position higher than the first character of the latter string among the 24 English letters, If it appears in the front position, the first string is considered small and
-1 is returned. If it appears later, the first string is considered larger and 1 is returned. If the compared characters are equal. Then compare the next character.
//ary为需要添加到页面中的数据数组 var op = document.getElementById("box");//获取容器 var myUl = op.getElementsByTagName("ul")[0];//获取列表 var arrLength = ary.length; for (var i = 0;i ' + (i + 5) + '' + ary[i].title; myUl.appendChild(oli);//动态添加元素 }Every addition will cause a DOM reflow. If the amount of data is too large, this will seriously affect performance. Regarding DOM reflow and redrawing, I recommend you read this article: http://www.css88.com/archives...Splicing strings:
var str = ""; for(var i=0; i<ary.length>'; str += '<span>'; str += (i+5); str += '</span>'; str += ary[i].title; str += ''; } myUl.innerHTML += str;</ary.length>Although this method only causes one reflow, it will remove all events and attributes from the original elements. If we add an event for the li tag in the list when the mouse moves in and the background changes color, this method will invalidate this event. In order to solve the problems caused by the above two data binding methods, we use document fragments to add data.
var frg = document.createDocumentFragment();//创建文档碎片 for (var i =0; i <ary.length>' + ( i + 5 ) + '' + ary[i].title; frg.appendChild(li);//将数据动态添加至文档碎片中 } myUl.appendChild(frg); //将数据一次性添加到页面中 frg = null; //释放内存</ary.length>This will only cause DOM reflow once and retain the original existing events.
4、DOM映射
DOM映射机制:所谓映射,就是指两个元素集之间元素相互“对应”的关系。页面中的标签集合和在JS中获取到的元素对象(元素集合)就是这样的关系。如果页面中的HTML标签结构发送变化,那么集合中对应的内容也会跟着自动改变。
- 1
- 2
- 3
- 4
- 5
对于这样一个列表使用下列脚本:
var myul = document.getElementById("myul"); var mylis = myul.getElementsByTagName('li'); for (var i = mylis.length - 1 ; i >= 0; i --) { myul.appendChild(mylis[i]); } console.log(mylis.length); // 5
将获取到的列表元素反序重新插入ul中,那么ul列表会变成下面这样:
- 5
- 4
- 3
- 2
- 1
我们看到列表的长度依然是5,只是位置颠倒了。这是因为每个li标签和JS中获取的标签对象存在一个对应关系,当某个标签被重新插入到页面中时,页面中对应的标签会移动到插入的位置。这就是DOM映射。
二、实现表格排序
1、使用ajax获取数据
之所以使用动态获取数据,是为了使用文档碎片绑定数据。
var res = ''; //声明一个全局变量,接收数据 var xhr = new XMLHttpRequest(); xhr.open('get', 'date.txt', false); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { res = JSON.parse(xhr.responseText); } } xhr.send(null);
此时数据就保存在了res
这个全局变量之中。
2、使用文档碎片绑定数据
var frg = document.createDocumentFragment(); for (let i = 0; i <h3 id="对表格进行排序">3、对表格进行排序</h3><p>这里涉及的点较多</p><pre class="brush:php;toolbar:false">//为两列添加点击事件 for (let i = 0; i <p>表格排序应用很常见,在面试中也会有这样的题目。这个小案例做下来,受益匪浅。这是我在学习的某峰学院的JS课程中的一个案例,如果对JS掌握不扎实的同学,欢迎保存:<code>链接: https://pan.baidu.com/s/1jHVy8Uq 密码: v4jk</code>。如果链接失效,加Q群领取:<code>154658901</code>。</p><p class="article fmt article__content"><br></p><p>I have been learning JS table sorting recently, but I didn’t expect that the inconspicuous table sorting actually implies many JS knowledge points. Record this learning process here. Hope it helps everyone too. </p><p>Complete table sorting involves the following knowledge points: </p>
call method uses
-
sort method in-depth
Data Binding
DOM Mapping
Function.prototype. Any function we define can be considered as an instance of the
Function class. Then you can find the prototype of the class through the
__proto__ attribute of the instance. Any function can call methods such as
call and
apply.
var obj = { name : 'JS' } function testCall () { console.log(this); } testCall.call( obj ); // {name: "JS"}First function
testCall finds the call method to execute through the prototype chain search mechanism. The call method calls the call method during the execution process. This in the instance is changed to the first parameter of call, and then the instance function of the call method is called and executed.
function fn1() { console.log(1); console.log(this); } function fn2() { console.log(2); console.log(this); } fn1.call(fn2); //this -> fn2 fn1.call.call(fn2); //这里的call是改变function.__proto__.call的call方法中的this,相当于执行参数When the call method is executed, the first parameter of the call method is used to change this, and starting from the second parameter is passed to The parameters of the function calling call. In non-strict mode, if no parameters are passed to the call method, or null or undefined is passed, this will point to
window.
sum.call(); //window sum.call(null); //window sum.call(undefined); //windowThe execution of call in strict mode is different from that in non-strict mode:
sum.call(); //undefined sum.call(null); //null sum.call(undefined); //undefinedThe following uses the call method to implement a method of converting an array-like array into an array:
function listToArray (likeAry) { var ary = []; try { ary = Array.prototype.slice.call(likeAry); } catch (e) { for (var i = 0; i and call Similar methods include the apply and bind methods, which are briefly summarized here. <p></p>The apply method has the same function as the call method, except that the form of passing parameters is different. apply wraps the parameters of the function in an array: <p></p><pre class="brush:php;toolbar:false">function sum(num1, num2) { console.log(num2 + num1); console.log(this); } sum.apply(null,[100,200]);The bind method is also used to change this key Literal, but it only changes the point of this and does not immediately execute the function that calls this.
function sum(num1, num2) { console.log(num2 + num1); console.log(this); } var obj = {name : 'zx'} var temp = sum.bind(obj); //temp已经是被改变了this的函数 temp(100,200); //当我们需要的时候才执行 //或者像这样处理 var temp = sum.bind(null, 100, 200); temp();The bind method embodies the preprocessing idea in js. 2. In-depth sortingWe know that the
sort method of an array can only sort arrays within 10. If there are numbers greater than 10 in the array that needs to be sorted, we need to pass the callback function to the
sort method. The common one is like this:
ary.sort(function (a,b) { return a - b; });This way, the array can be sorted in ascending order. . So what is the principle behind this sorting? For the two parameters passed in:
a represents the current item in the found array, and
b represents the item after the current item.
return a -b
: If a is greater than b, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is ascending order
return b -a
: If b is greater than a, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is descending order
var persons = [{ name:'dawei', age:55 },{ name:'ahung', age:3 },{ name:'maomi', age:2 },{ name:'heizi', age:78 },{ name:'afu', age:32 }];It’s actually very simple:
ary.sort(function(a,b){ return a.age - b.age; });If you sort by name, the
localeCompare() method of the string is involved:
ary.sort(function(a,b){ return a.name.localeCompare(b.name); });
name.localeCompare()This method will compare the letters of the two strings. If the first letter of the previous string appears in a position higher than the first character of the latter string among the 24 English letters, If it appears in the front position, the first string is considered small and
-1 is returned. If it appears later, the first string is considered larger and 1 is returned. If the compared characters are equal. Then compare the next character.
//ary为需要添加到页面中的数据数组 var op = document.getElementById("box");//获取容器 var myUl = op.getElementsByTagName("ul")[0];//获取列表 var arrLength = ary.length; for (var i = 0;i ' + (i + 5) + '' + ary[i].title; myUl.appendChild(oli);//动态添加元素 }Every addition will cause a DOM reflow. If the amount of data is too large, this will seriously affect performance. Regarding DOM reflow and redrawing, I recommend you read this article: http://www.css88.com/archives...Splicing strings:
var str = ""; for(var i=0; i<ary.length>'; str += '<span>'; str += (i+5); str += '</span>'; str += ary[i].title; str += ''; } myUl.innerHTML += str;</ary.length>Although this method only causes one reflow, it will remove all events and attributes from the original elements. If we add an event for the li tag in the list when the mouse moves in and the background changes color, this method will invalidate this event. In order to solve the problems caused by the above two data binding methods, we use document fragments to add data.
var frg = document.createDocumentFragment();//创建文档碎片 for (var i =0; i <ary.length>' + ( i + 5 ) + '' + ary[i].title; frg.appendChild(li);//将数据动态添加至文档碎片中 } myUl.appendChild(frg); //将数据一次性添加到页面中 frg = null; //释放内存</ary.length>This will only cause DOM reflow once and retain the original existing events.
4、DOM映射
DOM映射机制:所谓映射,就是指两个元素集之间元素相互“对应”的关系。页面中的标签集合和在JS中获取到的元素对象(元素集合)就是这样的关系。如果页面中的HTML标签结构发送变化,那么集合中对应的内容也会跟着自动改变。
- 1
- 2
- 3
- 4
- 5
对于这样一个列表使用下列脚本:
var myul = document.getElementById("myul"); var mylis = myul.getElementsByTagName('li'); for (var i = mylis.length - 1 ; i >= 0; i --) { myul.appendChild(mylis[i]); } console.log(mylis.length); // 5
将获取到的列表元素反序重新插入ul中,那么ul列表会变成下面这样:
- 5
- 4
- 3
- 2
- 1
我们看到列表的长度依然是5,只是位置颠倒了。这是因为每个li标签和JS中获取的标签对象存在一个对应关系,当某个标签被重新插入到页面中时,页面中对应的标签会移动到插入的位置。这就是DOM映射。
二、实现表格排序
1、使用ajax获取数据
之所以使用动态获取数据,是为了使用文档碎片绑定数据。
var res = ''; //声明一个全局变量,接收数据 var xhr = new XMLHttpRequest(); xhr.open('get', 'date.txt', false); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { res = JSON.parse(xhr.responseText); } } xhr.send(null);
此时数据就保存在了res
这个全局变量之中。
2、使用文档碎片绑定数据
var frg = document.createDocumentFragment(); for (let i = 0; i <h3 id="对表格进行排序">3、对表格进行排序</h3><p>这里涉及的点较多</p><pre class="brush:php;toolbar:false">//为两列添加点击事件 for (let i = 0; i <p>以上内容就是原生JS实现表格排序,希望能帮助到大家。</p><p><a href="http://www.php.cn/js-tutorial-371957.html" target="_self">js学习总结经典小案例之表格排序</a></p><p><a href="http://www.php.cn/js-tutorial-375121.html" target="_self">jquery中tablesorter表格排序组件是如何使用的?</a></p><p><a href="http://www.php.cn/js-tutorial-372544.html" target="_self">js表格排序实例详解(支持int,float,date,string四种数据类型)</a></p>
The above is the detailed content of Native JS implements table sorting. For more information, please follow other related articles on the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.