Home Web Front-end JS Tutorial Encapsulation of js methods commonly used during development (summary)

Encapsulation of js methods commonly used during development (summary)

Oct 11, 2018 pm 03:45 PM
javascript encapsulation

This article will introduce to you the js method encapsulation commonly used during development. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Determine whether it is an array

function isArray(arr){
return Object.prototype.toString.call(arr) ==='[object Array]';
}
 
isArray([1,2,3]) //true
Copy after login

2. Determine whether it is a function (three types)

function isFunction(fn) {
return Object.prototype.toString.call(fn) ==='[object Function]';
return fn.constructor == Function;
return fn instanceof Function;
return typeof (fn) == Function;
}
Copy after login

3. Array deduplication, only consider that the elements in the array are numbers or strings

function newarr(arr){
var arrs = [];
for(var i =0;i<arr.length;i++){
if(arrs.indexOf(arr[i])== -1){
arrs.push(arr[i])
}
}
return arrs;
}
Copy after login

4. Dynamic deduplication

var arr = [1,2, 3, 4];
function add() {
var newarr = [];
$(&#39;.addEle&#39;).click(() => {
var rnd = Math.ceil(Math.random() * 10);
newarr.push(rnd)
for (var i =0; i < newarr.length; i++) {
if (arr.indexOf(newarr[i]) == -1) {
arr.push(newarr[i])
arr.sort(function (a, b) {
return b - a //降序
});
}
}
console.log(arr)//[1,2,3,4,5,6,7,8,9]
})
}
add()
Copy after login

5. Remove string spaces (including three situations)

function trim(str) {
return str.replace(/^[" "||" "]*/,"").replace(/[" "|" "]*$/,"");// 去除头和尾
return str.replace(/\s/g,&#39;&#39;);//去除所有空格
return str.replace(/(\s*$)/g,"");//去除右边所有空格
}
Copy after login

6. Determine whether it is an email address

function isEmail(emailStr) {
var reg = /^[a-zA-Z0-9]+([._-]*[a-zA-Z0-9]*)*@[a-zA-Z0-9]+.[a-zA-Z0-9{2,5}$]/;
var result = reg.test(emailStr);
if (result) {
alert("ok");
} else {
alert("error");
}
}
Copy after login

7. Determine whether it is an email address Mobile phone number

function isMobilePhone(phone) {
var reg = /^1\d{10}$/;
if (reg.test(phone)) {
alert(&#39;ok&#39;);
} else {
alert(&#39;error&#39;);
}
}
Copy after login

8. Get the number of the first element in an object

function getObjectLength(obj){
var i=0;
for( var attrin obj){
if(obj.hasOwnProperty(attr)){
i++;
}
}
console.log(i);
}
var obj = {name:&#39;kob&#39;,age:20};
getObjectLength(obj) //2
Copy after login

9. Get the number of elements relative to the browser window Position, returns an {x,y} object

function getPosition(element) {
var offsety = 0;
offsety += element.offsetTop;
var offsetx = 0;
offsetx += element.offsetLeft;
if (element.offsetParent != null) {
getPosition(element.offsetParent);
}
return { Left: offsetx, Top: offsety };
} 
Copy after login

10. Determine the number of times a certain letter appears in the string

var str = &#39;To be, or not to be, that is the question.&#39;;
var count = 0;
var pos = str.indexOf(&#39;e&#39;);
while (pos !== -1) {
count++;
pos = str.indexOf(&#39;e&#39;, pos + 1);
}
console.log(count) //4
Copy after login

11 , Calculate the element with the most occurrences in the array

var arrayObj = [1,1, 2, 3, 3, 3,4, 5, 5];
var tepm = &#39;&#39;,count =0;
var newarr = new Array();
for(var i=0;i<arrayObj.length;i++){
if (arrayObj[i] != -1) {
temp = arrayObj[i];
}
for(var j=0;j<arrayObj.length;j++){
if (temp == arrayObj[j]) {
count++;
arrayObj[j] = -1;
}
}
newarr.push(temp + ":" + count);
count = 0;
}
for(var i=0;i<newarr.length;i++){
  console.log(newarr[i]);
}
Copy after login

12. Array filter (search function)

var fruits = [&#39;apple&#39;,&#39;banana&#39;, &#39;grapes&#39;,&#39;mango&#39;, &#39;orange&#39;];
function filterItems(query) {
return fruits.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}

console.log(filterItems(&#39;ap&#39;)); // [&#39;apple&#39;, &#39;grapes&#39;]
Copy after login

13. Copy object (No. A)

//第一种
var cloneObj =function(obj) {
var newObj = {};
if (obj instanceof Array) {
newObj = [];
}
for (var keyin obj) {
var val = obj[key];
newObj[key] = typeof val === &#39;object&#39; ? cloneObj(val) : val;
}
return newObj;
};
//第二种
function clone(origin , target){
var target = target || {};
for(var propin origin){
target[prop] = origin[prop];
}
return target;
} 
Copy after login

14. Deep cloning

var newObj ={};
function deepClone(origin,target){
var target = target || {},
toStr = Object.prototype.toString,
arrStr = "[object Array]";

for(var propin origin){
if(origin.hasOwnProperty(prop)){
if(origin[prop] != "null" && typeof(origin[prop]) == &#39;object&#39;){//判断原型链
target[prop] = (toStr.call(origin[prop]) == arrStr) ? [] : {}//判断obj的key是否是数组
deepClone(origin[prop],target[prop]);//递归的方式
}else{
target[prop] = origin[prop];
}
}
}
return target

}

deepClone(obj,newObj);
console.log(newObj)
Copy after login

15. Find the maximum and minimum value of the array

Array.prototype.max = function(){
return Math.max.apply({},this)
}
 
Array.prototype.min = function(){
return Math.min.apply({},this)
}
 
console.log([1,5,2].max())
Copy after login

16. JSON array deduplication

function UniquePay(paylist){
var payArr = [paylist[0]];
for(var i =1; i < paylist.length; i++){
var payItem = paylist[i];
var repeat = false;
for (var j =0; j < payArr.length; j++) {
if (payItem.name == payArr[j].name) {
repeat = true;
break;
}
}
if (!repeat) {
payArr.push(payItem);
}
}
return payArr;
} 
Copy after login

17. Compare two arrays and take out the intersection

Array.intersect = function () {
var result = new Array();
var obj = {};
for (var i =0; i < arguments.length; i++) {
for (var j =0; j < arguments[i].length; j++) {
var str = arguments[i][j];
if (!obj[str]) {
obj[str] = 1;
}
else {
obj[str]++;
if (obj[str] == arguments.length)
{
result.push(str);
}
}//end else
}//end for j
}//end for i
return result;
}
console.log(Array.intersect(["1","2", "3"], ["2","3", "4", "5", "6"]))
Copy after login

18. Array sum Object comparison. Remove the object whose key is the same as the array element

var arr = [&#39;F00006&#39;,&#39;F00007&#39;,&#39;F00008&#39;];
var obj = {&#39;F00006&#39;:[{&#39;id&#39;:21}],&#39;F00007&#39;:[{&#39;id&#39;:11}]}
var newobj = {};
for(var itemin obj){
if(arr.includes(item)){
newobj[item] = obj[item]
}
}
console.log(newObj)
Copy after login

19. Delete an element in the array

//第一种
Array.prototype.remove = function(val){
var index = this.indexOf(val);
if(index !=0){
this.splice(index,1)
}
}
[1,3,4].remove(3)
//第二种
function remove(arr, indx) {
for (var i =0; i < arr.length; i++) {
var index = arr.indexOf(arr[i]);
if (indx == index) {
arr.splice(index, 1)
}
}
return arr
}
Copy after login

20. Determine whether the array contains an element Element

Array.prototype.contains = function (val) {
for (var i =0; i < this.length; i++) {
if (this[i] == val) {
return true;
}
}
return false;
};

[1, 2,3, 4].contains(2)//true
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit JavaScript Video Tutorial!

Related recommendations:

php public welfare training video tutorial

JavaScript graphic tutorial

JavaScriptOnline Manual

The above is the detailed content of Encapsulation of js methods commonly used during development (summary). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

See all articles