Commonly used JavaScript operations on the front end (code examples)
The content this article brings to you is about commonly used JavaScript operations (code examples) on the front end. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Delete a specified character in the string
Example: Delete km in "10km"
var str = "10km" //方法一: var res = str.replace('km', '') //方法二: var res = str.split('km').join('') //join方法不传参默认使用逗号作为分隔符
2. Array deduplication
var arr = [1, 2, 3, 1, 2] //方法一: var res = [...new Set(arr)] //方法二: var res = Array.from(new Set(arr)) //方法三: var res = []; for (var i in arr) { if (res.indexOf(arr[i] === -1) { res.push(arr[i]) } } //方法四: var res = [] arr.map((item, index) => { if (res.indexOf(item) === -1){ res.push(item) } })
Attachment: Usage of Array.from():
Array.from(arr, mapfn, thisArg): used to convert two types of objects into real arrays.
Array-like object (must have length attribute)
Traversable object (String with Iterator interface deployed, new in ES6 Map and Set).
Parameters: The first is an array, which must be passed; the second is a function (similar to the map function), which operates on the array elements and then returns the array, optional; the third The first is a pointer to the this keyword, optional.
var obj1 = { 0: 'a', 1: 'b', 2: 'c' } var arr1 = Array.from(obj1) console.log(arr1) // [] /* 1. 类数组对象,具有length属性,而普通对象是没有length属性的。*/ /* 2. 类数组对象的属性名必须为非负整数,对象中的属性名会被当做字符串处理。*/ var obj2 = { 0: 'a', 1: 'b', 2: 'c', length: 2 } var arr2 = Array.from(obj2) console.log(arr2) // ["a", "b"] var obj3 = { 0: 'a', 1: 'b', 2: 'c', length: 4 } var arr3 = Array.from(obj3) console.log(arr3) // ["a", "b", "c", undefined] var obj4 = { 0: 'a', 1: 'b', 2: 'c', length: 3 } var arr4 = Array.from(obj4, item => item + 1) console.log(arr4) // ["a1", "b1", "c1"] var obj5 = { "1": "a", "0": "b", length: 2 } var arr5 = Array.from(obj5) console.log(arr5) // ["b", "a"]
3. Convert pseudo-array object into array
var obj = { 0: 'a', 1: 'b', length: 2 } //方法一: Array.from(obj) //方法二: Array.prototype.slice.call(obj) //方法三: Array.prototype.concat.apply([], obj) //方法四: Array.prototype.splice.call(obj, 0) // 返回被删除的元素,原对象obj会被破坏掉 console.log(obj) // obj: {length: 0} // 上述的Array.prototype 均可用[]代替
4. Deep copy of array or object
//方法一: JSON.parse(JSON.stringify(obj)) //方法二:递归遍历 function clone (obj) { var res = obj.constructor === Array ? [] : {} for (var i in obj) { res[i] = typeof obj[i] === 'object' ? clone(obj[i]) : obj[i] // 即obj[i]为数组或对象,继续拷贝 } return res } //附:数组浅拷贝 var arr = ['a', ['b', ['c']]] //1.使用slice() var res = arr.slice(0) console.log(res) // ['a', ['b', ['c']]] res[1][1] = 'b' console.log(res) // ['a', ['b', ['b']]] console.log(arr) // ['a', ['b', ['b']]] //2.使用concat() var arr = ['a', ['b', ['c']]] var res = [].concat(arr) res[1][1] = 'b' console.log(res) // ['a', ['b', ['b']]] console.log(arr) // ['a', ['b', ['b']]] //Object.assign()也只能实现对象的浅拷贝,它只是一级属性复制,比浅拷贝多深拷贝了一层 var obj = {a: "a", b: {c: "d"}} var res = Object.assign({}, obj) res.b.c= "e" console.log(res) // {a: "a", b: {c: "e"}} console.log(obj) // {a: "a", b: {c: "e"}}
5. No block-level scope leads to inner variable coverage outer variables.
var date = new Date().getDate(); function f(){ console.log(date); if(false){ var date = 0;//变量提升 } } f();//undefined
6. Usage of tag templates in ES6:
let a = 1; let b = 2; function tag(arr, value1, value2){ console.log(arr); //["hello ", " world ", ""] console.log(value1); //3 console.log(value2); //2 } tag`hello ${a + b} world ${a * b}`; /** 如果函数名后的模板字符串中没有变量,则直接将其作为函数参数调用。 如果存在变量则先将模板字符串处理成多个参数,再调用函数。 处理规则: 1.默认该函数第一个参数为数组,该数组的成员是模板字符串中那些没有变量替换的部分。 2.变量替换只发生在数组的第一个成员与第二个成员之间、第二个成员与第三个成员之间。 以此类推,故arr中第三个成员为"",原因是${a * b}的变量替换发生在第二个成员与第三个成员之间, 所以必须存在第三个成员。 3.函数的其他参数,都是模板字符串各个变量被替换后的值。 函数形如: function tag(stringArr, ...value){} */
The above is the complete introduction, if you want to know more about HTML video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of Commonly used JavaScript operations on the front end (code examples). For more information, please follow other related articles on the PHP Chinese website!

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...


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

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

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.
