Home > Web Front-end > HTML Tutorial > Commonly used JavaScript operations on the front end (code examples)

Commonly used JavaScript operations on the front end (code examples)

云罗郡主
Release: 2018-10-17 15:05:48
forward
2448 people have browsed it

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方法不传参默认使用逗号作为分隔符
Copy after login

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)
	}
})
Copy after login

Attachment: Usage of Array.from():

Array.from(arr, mapfn, thisArg): used to convert two types of objects into real arrays.

  1. Array-like object (must have length attribute)

  2. 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"]
Copy after login

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 均可用[]代替
Copy after login

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"}}
Copy after login

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
Copy after login

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){}
*/
Copy after login

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template