Array, character, object, regular API summary

I was afraid that I would delete things and delete my notes, so I organized them on csdn. These are my usual study notes, and they may be a bit verbose... If there are any omissions or errors, please point them out to someone passing by! Learn together and make progress together!

array

join

arr.join('connector') will not change the original array

Use connectors to connect the elements in the array into strings, and arr.join('') achieves seamless connection

var arr=['我','是','蛋','蛋']

var arr1=arr.join('-') console.log(arr1); // 我-是-蛋-蛋

var arr2=arr.join('') console.log(arr2); // 我是蛋蛋

concat

arr.concat('a','b',arr1) will not change the original array

If a parameter passed to concat() is itself an array, the elements of the array will be connected to arr instead of the array itself.

var arr=['我','是','蛋','蛋']

var arr1=['我','真','好','看']

var arr2=arr.concat(arr1)

console.log(arr2); // ['我', '是', '蛋', '蛋', '我', '真', '好', '看']

var arr3=arr.concat(['呀',['哈','哈','哈']],arr1)

console.log(arr3); // ['我', '是', '蛋', '蛋', '呀', ['哈', '哈', '哈'], '我', '真', '好', '看']

console.log(arr); // ['我', '是', '蛋', '蛋']

intercept sclice

arr.slice(start,end)/arr.slice(start) will not change the original array

The intercepted array contains start but does not contain end.

If end is omitted, it means intercepting from the start position to the end.

Supports negative numbers, indicating the last number

var arr=['我','是','蛋','蛋']

var arr1=arr.slice(1)

console.log(arr1); // ['是', '蛋', '蛋']

var arr2=arr.slice(2,4)

console.log(arr2); // ['蛋', '蛋']

var arr3=arr.slice(-3)

console.log(arr3); // ['是', '蛋', '蛋']

var arr4=arr.slice(-4,-2)

console.log(arr4); // ['我', '是']

console.log(arr); // ['我', '是', '蛋', '蛋']

Delete, insert, replace splice

arr.splice(start,deleteCount,value1,value2...) will modify the original array and return the sub-elements composed of the deleted elements

If deleteCount is 0, it means inserting an element, and the inserted element will be ranked before start.

If it is deleted, start from start and include start

If it is a replacement, parameter 1 is the starting position of the replaced element, parameter 2 is the number of elements that need to be replaced, and parameters 3-n are all elements that need to be replaced.

var arr=['我','是','蛋','蛋','我','真','好','看'] // 删除

var arr1=arr.splice(0,2)

console.log(arr1); // ['我', '是']

console.log(arr); // ['蛋', '蛋', '我', '真', '好', '看']

// 插入

var arr2=arr.splice(2,0,'哈','哈')

console.log(arr2); // []

console.log(arr); // ['我', '是', '哈', '哈', '蛋', '蛋', '我', '真', '好', '看']

// 替换 参数1:替换元素的起始位置,参数2:需要替换元素的个数,参数3……n:需要插入的元素

var arr3=arr.splice(2,1,'哈','哈')

console.log(arr3); // ['蛋']

console.log(arr); // ['我', '是', '哈', '哈', '蛋', '我', '真', '好', '看']

flip reverse

arr.reverse() will modify the original array and return the modified array

var arr=['我','是','蛋','蛋','我','真','好','看'] 

var arr1=arr.reverse() 

console.log(arr1); // ['看', '好', '真', '我', '蛋', '蛋', '是', '我'] 

console.log(arr); // ['看', '好', '真', '我', '蛋', '蛋', '是', '我']

sortsort

arr.sort() will modify the original array and return the modified array

var arr=['我','是','蛋','蛋','我','真','好','看'] // 默认按照数组元素第一位的ascll码从小到大排列

var arr1=arr.sort()

console.log(arr); // ['好', '我', '我', '是', '看', '真', '蛋', '蛋']

console.log(arr1); // ['好', '我', '我', '是', '看', '真', '蛋', '蛋']

// 升序 只限数组中的数字或者数字字符串

var arr=[1,2,3,2,5,6,4,3,7,1,2]

var arr2=arr.sort(function(a,b){return a-b})

console.log(arr); // [1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 7]

console.log(arr2); // [1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 7]

// 降序 只限数组中的数字或者数字字符串

var arr=[1,2,3,2,5,6,4,3,7,1,2]

var arr3=arr.sort(function(a,b){return b-a})

console.log(arr); // [7, 6, 5, 4, 3, 3, 2, 2, 2, 1, 1]

console.log(arr3); // [7, 6, 5, 4, 3, 3, 2, 2, 2, 1, 1]

// 随机打乱数组 数组中可以是任何数据类型

var arr=[1,2,3,2,5,6,4,3,7,1,2]

var arr4=arr.sort(function(){ return Math.random()>.5?1:-1 })

console.log(arr); // [3, 1, 2, 3, 5, 2, 4, 2, 7, 1, 6]

console.log(arr4); // [3, 1, 2, 3, 5, 2, 4, 2, 7, 1, 6]

Find indexOf/lastIndexOf

arr.indexOf(value,searchStartIndex)/arr.lastIndexOf(value,searchStartIndex) will not change the original array

indexOf is checked from front to back, lastIndexOf is checked from back to front, and the second parameter of lastIndexOf is also counted from back to front.

value is the element to be searched, and searchStartIndex specifies the position to start searching in the string. Its legal values ​​are 0 to arr.length - 1. If this parameter is omitted, the search will start from the first character of the string.

If the index of the return value in the array is found, -1 is returned if not found.

indexOf can match objects pointing to the same address

var arr=['我','是','蛋','蛋','我','真','好','看']

var element=arr.indexOf('真')

var element1=arr.lastIndexOf('好')

var element2=arr.indexOf('真',6)

var element3=arr.lastIndexOf('好',3)

console.log(arr); // ['我', '是', '蛋', '蛋', '我', '真', '好', '看']

console.log(element); // 5

console.log(element1); // 6

console.log(element2); // -1

console.log(element3); // -1

loopforEach

arr.forEach(function(value,index,arr){}) will not change the original array and has no return value

value is the element of each loop, index is the index of the loop element, and arr is the original array.

loop map

arr.map(function(value,index,arr){}) will not change the original array and has a return value

value is the element of each loop, index is the index of the loop element, and arr is the original array.

 // 求平方
var data = [1, 2, 3, 4, 5]
var newData = data.map(function (item) {
    return item * item
})
console.log(newData); // [1, 4, 9, 16, 25]
// 箭头函数
var newData1 = data.map(item => item * item)
console.log(newData1); // [1, 4, 9, 16, 25]

// 获取数组对象中的特定属性值
var users = [
    { "name": "蛋蛋", "email": "[email protected]" },
    { "name": "连连", "email": "[email protected]" },
    { "name": "薇薇", "email": "[email protected]" }
]
var newName = users.map(function (item) {
    return item.name
})
console.log(newName); // ['蛋蛋', '连连', '薇薇']

// 第2种获取数组对象中的值
let name = []
users.map(function (item) {
    name.push(item.name)
})
console.log(name); // ['蛋蛋', '连连', '薇薇']

// 用map()调用一个方法的使用
// 字符串转整数
let arrr = ['1', '2', '3']
function returnInt(e) {
    return parseInt(e)
}
let newArr = arrr.map(returnInt)
console.log(newArr); // [1, 2, 3]

// 接口数据映射,从接口得到数据res
let r = res.map(item => {
    return {
        title: item.name,
        sex: item.sex === 1 ? '男' : item.sex === 0 ? '女' : '保密',
        age: item.age,
        avatar: item.img
    }
})

// js模拟实现数组的map方法
// 思路:直接Array.map()就可以调用map方法,它应该在原型连上,然后接收一个匿名函数作为参数,通过循环调用传入的匿名函数
Array.prototype.newMap=function(e){
    let newArr=[]
    for(let i=0;i<this.length;i++){
        newArr.push(e(this[i],i,this))
    }
    return newArr
}
let arrData=['1','2','3']
arrData.newMap((item,index,arr)=>{
    console.log(item,index,arr);
})

Array to string toString/String

String(arr)/arr.toString() will not change the original array

Concatenate the elements of the array into a string using commas, similar to arr.join(',')

let tostring=[1,2,3,4]

let newTostring=tostring.toString()

console.log(newTostring); // 1,2,3,4

console.log(tostring); // [1,2,3,4]

let newTostring1=String(tostring)

console.log(newTostring1); // 1,2,3,4

console.log(tostring); // [1,2,3,4]

Push unshift at the beginning

arr.unshfit(value1,value2...) changes the original array and returns the length of the new array

Insert element at the beginning of the array

var unshiftArr=[1,2,3,4]
var unshiftArr1=unshiftArr.unshift(8,9)
console.log(unshiftArr); // [8, 9, 1, 2, 3, 4]
console.log(unshiftArr1); // 6

var unshiftArr=[1,2,3,4]
var unshiftArr2=unshiftArr.unshift([8,9])
console.log(unshiftArr); // [[8,9], 1, 2, 3, 4]
console.log(unshiftArr2);// 5

Start popping shfit

arr.shfit() changes the original array and returns the popped element

Pop the first element of the array

var shiftArr=[2,3,1,4,5] 

var shiftArr1=shiftArr.shift() 

console.log(shiftArr1); // 2 

console.log(shiftArr); // [3, 1, 4, 5]

end push

arr.push(value1,value2...) changes the original array and returns the length of the new array

Append elements to the end of the array. The appended array will not be scattered.

var pushArr=[1,2,3,4,5]
var pushArr1=pushArr.push(2,3)
console.log(pushArr); // [1, 2, 3, 4, 5, 2, 3]
console.log(pushArr1); // 7

var pushArr=[1,2,3,4,5]
var pushArr2=pushArr.push([6,7])
console.log(pushArr); // [1, 2, 3, 4, 5, [6,7]]
console.log(pushArr2); // 6

pop at the end

arr.pop() changes the original array and returns the popped element

Pop the last element of the array

var popArr=[1,2,3,7,4,5] 

var popArr1=popArr.pop() 

console.log(popArr); // [1, 2, 3, 7, 4] 

console.log(popArr1); // 5

Array.every

If all conditions are met , the original array will not be changed and a Boolean value will be returned.

var everyArr=[1,2,3,4,5]
 
var everyArr1=everyArr.every(item=>{ return item>0 }) 

var everyArr2=everyArr.every(item=>{ return item>3 }) 

console.log(everyArr1); // true 

console.log(everyArr2); // false

Array.some

If the condition is partially met , the original array will not be changed and a Boolean value will be returned.

Determine whether there are elements in the array that meet the conditions, and exit the loop as long as it encounters elements that meet the conditions.

var someArr=[1,2,3,4,5,6] 

var someArr1=someArr.some(item=>{ return item>3 }) 

var someArr2=someArr.some(item=>{ return item>6 }) 

console.log(someArr1); // true 

console.log(someArr2); // false

Array.filter

Filtering by conditions does not change the original array and returns a new array containing elements that meet the conditions.

const persons = [
    { name: 'Dandan', age: 18 },
    { name: 'Lianlian', age: 17 },
    { name: 'Weiwei', age: 20 }
]

let filterArr=persons.filter(item=>{
    return item.age>=18
})
console.log(filterArr); // [{name: 'Dandan', age: 18},{name: 'Weiwei', age: 20}]

Array.reduce

The original array will not be changed

Parameter 1: callback function

        Function parameters: Parameter 1: The value returned from the last loop, which is the initial value for the first loop.

                        Parameter 2: The value of the current loop

                        Parameter 3: Index of the current value

                        Parameter 4: Original array

Parameter 2: Initial value, optional. When no initial value is specified, the first element of the array will be used as the initial value.

// 累加
let reduceArr = [1, 2, 3, 4, 5, 6, 7]
let reduceArr1 = reduceArr.reduce((total, value, index, arr) => {
    return total + value
}, 0)
console.log(reduceArr1); // 28

// 第二种写法
let reduceArr2 = reduceArr.reduce((x, y) => {
    return x + y
})
console.log(reduceArr2); // 28

// 数组处理
const people = [
    { name: 'Dandan', age: 18 },
    { name: 'Lianlian', age: 17 },
    { name: 'Weiwei', age: 20 }
]
let names = people.reduce((total, value) => {
    if (value.age >= 18) {
        total.push(value.name)
    }
    return total
}, [])
console.log(names); // ['Dandan', 'Weiwei']

// 将数组转化为对象
const user = [
    { id: '1', name: 'Jim' },
    { id: '2', name: 'Lily' },
    { id: '3', name: 'Allen' }
]

let obj=user.reduce((total,value)=>{
     return {...total,[value.id]:value}
},{})
console.log(obj);
// {
//    1:{id: '1', name: 'Jim'}
//    2:{id: '2', name: 'Lily'}
//    3:{id: '3', name: 'Allen'}
// }

// 将二维数组扁平化为一维数组
const intro=[['我','是','蛋','蛋'],['我','真','好','看']]
let intro1=intro.reduce((total,value)=>{
    return total.concat(value)
},[])
console.log(intro1); // ['我', '是', '蛋', '蛋', '我', '真', '好', '看']

// 在一次遍历中进行多次计算
// 寻找最大值最小值
const read=[1,2,3,1,4,0.4,0.9,5.6]
const initMinMax={
    min:Number.MAX_VALUE,
    max:Number.MIN_VALUE
}
const minMax=read.reduce((total,value)=>{
    return {
        min:Math.min(total.min,value),
        max:Math.max(total.max,value)
    }
},initMinMax)
console.log(minMax); // {min: 0.4, max: 5.6}

// 获取数组中的最大值
let maxArr=[12,13,24,45,23,56]
let max=maxArr.reduce(function(x,y){
    return x>y?x:y
})
console.log(max); // 56

Array.reduceRight

The original array will not be changed

It works the same as reduce(), the difference is that it processes the array from high to low (right to left)

var rightArr=[2,10,60]

var rightArr1=rightArr.reduceRight(function(x,y){ return x/y })

console.log(rightArr1); // 3

Array.find

Returns the first array member that meets the conditions. If not found, returning undefined will not change the original array.

var findArr = [
    { id: 1, name: 'Dandan', age: 17 },
    { id: 2, name: 'Lianlian', age: 17 },
    { id: 3, name: 'Weiwei', age: 20 }
]
var findArr1=findArr.find(item=>{
    return item.age===17
})
console.log(findArr1); // {id: 1, name: 'Dandan', age: 17}

Array.findIndex

Find the index of the first array element that meets the conditions. If not found, returning -1 will not change the original array.

var findIndexArr=[
    { id: 1, name: 'Dandan', age: 17 },
    { id: 2, name: 'Lianlian', age: 17 },
    { id: 3, name: 'Weiwei', age: 20 }
]
let findIndexArr1=findIndexArr.findIndex(item=>{
     return item.age===17
})
console.log(findIndexArr1); // 0

Array.includes

Finds whether a certain value is included in the array. It does not accept function parameters. If it does, it returns true. If it does not, it returns false and it will not change the original array.

let includesArr=[1,2,3,4]

let includesArr1=includesArr.includes(2)

console.log(includesArr1); // true

Array.toLocaleString

Convert an array to a localized string. It calls the toLocaleString() method on all array elements and then concatenates the resulting strings using locale-specific delimiters without changing the original array.

Array.from

Array.from(arr,f) will not change the original array

When there is only parameter 1, parameter 1 is converted into an array. Parameter 2 can be a callback function to calculate or conditionally filter the array elements.

var arr='dandan'
var arr1=[1,2,3,4]
var arr2=Array.from(arr)
console.log(arr2); // ['d', 'a', 'n', 'd', 'a', 'n']
var arr3=Array.from(arr1,x=>x+x)
console.log(arr3); // [2, 4, 6, 8]
console.log(arr); // dandan
console.log(arr1); // [1, 2, 3, 4]

Array.isArray

Array.isArray(arr) determines whether it is an array without changing the original array and returns a Boolean value

var arr=[1,2,3]

var arr1=Array.isArray(arr)

console.log(arr1); //true

var arr={name:'dandan'}

var arr1=Array.isArray(arr)

console.log(arr1); // false

Convert multi-dimensional array to low-dimensional array flat

arr.flat(index) converts a multi-dimensional array into a low-dimensional array. Index is the number of expansion levels. If not passed, the default expansion level will not change the original array.

var arr = [1, [1, 2, 3], [2, 3, [4, 5, 6]]]

console.log(arr.flat(2)); // [1, 1, 2, 3, 2, 3, 4, 5, 6]

console.log(arr); // [1, [1, 2, 3], [2, 3, [4, 5, 6]]]

flatMap

arr.flatMap(currentValue,index,array) The combination of map and flat, because map cannot handle multi-dimensional arrays and will not change the original array

var arr = [1, [1, 2, 3], [2, 3, [4, 5, 6]]]
var map = arr.flatMap((item) => item)
console.log(map); // [1, 1, 2, 3, 2, 3, [4, 5, 6]] 展开一层
console.log(arr); // [1, [1, 2, 3], [2, 3, [4, 5, 6]]]

An example~

// 需要把Authorized等于2的过滤掉,然后再转换成Select下拉组件需要的格式  
// [
//  {
//      text: '公司名称',
//      value: '公司ID'
//  }
// ]
const studioList = [
    {
        Authorized: "2",
        CompanyType: "1",
        Id: "3729",
        Name: "哈哈哈哈哈",
        ServiceProviderId: "6",
        TenantId: "1",
    },
    {
        Authorized: "1",
        CompanyType: "1",
        Id: "3134",
        Name: "纳税统计-启用时间202101无期初",
        ServiceProviderId: "6",
        TenantId: "1",
    },
    {
        Authorized: "1",
        CompanyType: "1",
        Id: "427",
        Name: "美丽人生工作室",
        ServiceProviderId: "6",
        TenantId: "1",
    },
    {
        Authorized: "1",
        CompanyType: "1",
        Id: "410",
        Name: "凭证测试专用2",
        ServiceProviderId: "6",
        TenantId: "1",
    }
]
// 方法1 filter+map
const filterList = studioList.filter(r => r.Authorized === '1').map(i => ({ text: i.Name, value: i.Id }))
console.log(filterList); // [{text: "纳税统计-启用时间202101无期初",value: "3134"},{text: "美丽人生工作室",value: "427"},{text: "凭证测试专用2",value: "410"}]

// 方法2 flatMap
const filterList1 = studioList.flatMap(r => r.Authorized === '1' ? [{text: r.Name, value: r.Id}] : [])
console.log(filterList1); // [{text: "纳税统计-启用时间202101无期初",value: "3134"},{text: "美丽人生工作室",value: "427"},{text: "凭证测试专用2",value: "410"}]

Summarize

API to change the original array

  • splice (deletion, insertion, replacement): returns the deleted element subarray
  • reverse (flip): Return the modified array
  • sort: Returns the modified array
  • unshfit (push on the stack at the beginning): Return the modified array
  • shfit (pop at the beginning): Return the modified array
  • push (end push): return the modified array
  • pop (end pop): return the modified array

API that does not change the original array

  • join (connection): Returns the string after the connection
  • concat (splicing): Returns the concatenated array
  • sclice (interception): Returns the subarray intercepted according to conditions
  • indexOf(search)/lastIndexOf(search from back to front):
  • forEach (loop): no return value
  • map (loop): has a return value
  • toString/String (convert to string): Return the converted string
  • every (find all that match the conditions): true/false
  • some (find part that meets the conditions): true/false
  • filter: Returns a new array containing all elements that meet the filter conditions
  • reduce(accumulate): Return the new array after modification
  • reduceRight (accumulate from back to front): Return the new array after modification
  • find (find element): Return the first element that meets the conditions (return in array form)
  • findIndex (find element index): the index of the first element in the range that meets the conditions
  • includes: true/false
  • toLocaleString(): Convert array to localized string
  • isArray (judgment array): determine whether it is an array and return a Boolean value
  • from(): Convert a string into an array, or perform some calculations
  • isArray (judgment): determine whether it is an array and return a Boolean value
  • flat (dimensionality reduction): convert multi-dimensional arrays into low-dimensional arrays
  • flatMap(): combination of flat and map

Generate a new array without changing the original array

join、concat、sclice、map、every、some、filter、reduce、from、find

indexOf/lastIndexOf, find, findIndex comparison

  • indexOf/lastIndexOf: Find the position where the element first appears in the array. Parameter 1 is the element to be found, and parameter 2 can limit the search range. If the element index is found, -1 is returned if not found.
  • find: Returns the first element that meets the conditions. If it cannot be found, it returns undefined. The parameter is the callback function.
  • findIndex: Returns the position of the first element that meets the conditions. If it is not found, it returns -1. The parameter is the callback function.

Comparison of map, forEach, every, some, reduce

  • forEach: just a simple loop, no return value, the parameter is a function, the function has 3 parameters, parameter 1: current value, parameter 2: index of the current value, parameter 3: original array
  • map: returns a new array, the parameters are functions
  • every: All elements in the array return true if they meet the conditions, and false if one of them does not meet the conditions.
  • some: Returns true if some of the conditions are met, returns false if all of them are not met.
  • reduce: You can perform calculations or other operations on array elements and return the operation results.

string

Create a tag anchor

str.anchor(name) creates an a tag, str is the content of the a tag, and name is the name attribute value of the a tag.

var str='我是a标签内容'
var str1=str.anchor('name属性值')
console.log(str1); // <a name="name属性值">我是a标签内容</a>

Create b label bold

var str='Dandan'
var str1=str.charAt()
var str2=str.charAt(2)
console.log(str1); // D
console.log(str2); // n

charAt

str.charAt(index) searches for the character at the specified position. index is the index of the character to be searched for. If the index is not passed, the default is 0.

var str='Dandan'

var str1=str.charAt()

var str2=str.charAt(2)

console.log(str1); // D

console.log(str2); // n

Splicing concat

str.concat(value1,value2……) concatenates multiple strings together

var str ='Dan'

var str1='dan'

var str2='我是'.concat(str,str1,'!')

console.log(str2); // 我是Dandan!

endsWith

str.endsWith(value) determines whether str ends with value and returns true/false

var str='I am Dandan'

var str1=str.endsWith('n')

var str2=str.endsWith('an')

var str3=str.endsWith('a')

console.log(str1,str2,str3); // true true false

startsWith

str.startssWith(value) determines whether str starts with value and returns true/false

var str='I am Dandan'

var str1=str.startsWith('I')

var str2=str.startsWith('I ')

var str3=str.startsWith('a')

console.log(str1,str2,str3); // true true false

includesincludes

str.includes() determines whether a string contains another string and returns true/false

var str='My name is Dandan'

var str1=str.includes('name')

var str2=str.includes('is Dandan')

var str3=str.includes('you')

console.log(str1,str2,str3); // true true false

Find indexOf

str.indexOf(value,index) Parameter 1: the string to be searched for; Parameter 2: from which position to search. Returns the index of the first occurrence of the string in the original string. If not found, -1 is returned.

var str='My name is Dandan'

var index=str.indexOf('name')

var index1=str.indexOf(' is',2)

var index2=str.indexOf('you')

console.log(index,index1,index2); // 3 7 -1

Find lastIndexOf

str.lastIndexOf(value,index) Parameter 1: The string to be found; Parameter 2: From which position to search forward. Returns the index of the last occurrence of the string in the original string. If not found, -1 is returned.

var str='My name is Dandan'

var index=str.lastIndexOf('name')

var index1=str.lastIndexOf('name',9) // 从第9个开始往前查找首次出现name的位置

var index2=str.lastIndexOf('you')

console.log(index,index1,index2); // 3 3 -1

str.link(linkLocation) creates an a tag with a link address, linkLocation is the link address

var str='这是一个带link的a标签'

var str1=str.link('www.baidu.com')

console.log(str1); // <a href="www.baidu.com">这是一个带link的a标签</a>

at End

str.padEnd(lenght,str1) Parameter 1 is the expected length of the target string. Parameter 2 is if the length of the string does not reach the expected length, use parameter 2 to add to the end of the string in a loop until the expected length is reached.

var str='dandan' var str1=str.padEnd(7) // 没有参数2就用空格代替

var str2=str.padEnd(2,'haha') // 如果期望长度小于目标字符串,直接返回目标字符串,什么也不做

var str3=str.padEnd(9,'12')

var str4=str.padEnd(9,'12234567')

console.log(str1); // dandan 后面有空格

console.log(str2); // dandan

console.log(str3); // dandan121

console.log(str4); // dandan122

pathStart

str.padStart(lenght,str1) Parameter 1 is the expected length of the target string. Parameter 2 is if the string length does not reach the expected length, use parameter 2 to add to the beginning of the string in a loop until the expected length is reached.

var str='dandan'

var str1=str.padStart(7) 

var str2=str.padStart(2,'haha')

var str3=str.padStart(9,'12')

var str4=str.padStart(9,'12234567')

console.log(str1); // 前面有个空格 dandan

console.log(str2); // dandan

console.log(str3); // 121dandan

console.log(str4); // 122dandan

repeatrepeat

str.repeat(num) repeats a string, num is the number of repetitions, the decimal will be rounded down, and passing in 0 returns an empty string.

var str='dan'

var str1=str.repeat(0) //

var str2=str.repeat(2) // dandan

var str3=str.repeat(3.5) // dandandan

Find search

str.search() searches for the first occurrence of a string and returns -1 if not found. Regular expressions can be passed

var str='My name is Dandan'

var index=str.search('name')

var index1=str.search('you')

var index2=str.search(/is/)

console.log(index,index1,index2); // 3 -1 8

intercept sclice

str.sclice(index1,index2) intercepts a string, parameter 1: the starting position of interception; parameter 2: the end position of interception. If parameter 2 is not passed, it will be intercepted to the end of the string. If parameter 2 is a negative number, it will be intercepted to the str.length+index2 position.

var str='My name is Dandan'

var str1=str.slice(1)

var str2=str.slice(1,7)

var str3=str.slice(0,-1)

console.log(str1); // y name is Dandan

console.log(str2); // y name

console.log(str3); // My name is Danda

split split

str.split(value,index) splits a string into an array. Remove the value string, use value as the dividing point, divide the original string into several elements, and index is the number of elements retained in the array. The index does not need to be passed.

var str='My name is Dandan'

var str1=str.split()

var str2=str.split(' ',3)

var str3=str.split('m')

var str4=str.split('name')

console.log(str1); // ['My name is Dandan']

console.log(str2); // ['My', 'name', 'is']

console.log(str3); // ['My na', 'e is Dandan']

console.log(str4); // ['My ', ' is Dandan']

intercept substr

str.substr(index1,index2) starts from the specified position to the specified number of strings. If the starting position, which is the first string, is greater than the length of the string, an empty string is returned. The second position exceeds the remaining length of the string. , the default is the remaining length of the string. If it is a negative number, it is the length of the string plus the negative number.

var str='My name is Dandan'

var str1=str.substr(3)

var str2=str.substr(-3)

var str3=str.substr(3,3)

console.log(str1); // name is Dandan

console.log(str2); // dan

console.log(str3); // nam

Intercept substring

str.substring(index1,index2) intercepts the string between two indexes. index1 and index2 are both integers. If it is less than 0, it will be converted to 0. If it is greater than the string length, it will be converted to the string length. If the second If one parameter is greater than the first parameter, the positions of the two parameters will be swapped by default.

var str='My name is Dandan'

var str1=str.substring(1,4)

var str2=str.substring(4,1)

console.log(str1); // y n

console.log(str2); // y n

Convert to lowercase toLocaleLowerCase

str.toLocaleLowerCase() converts the string to lowercase

var str='My name is Dandan'

var str1=str.toLocaleLowerCase()

console.log(str1); // my name is dandan

Convert to uppercase toLocaleUpperCase/toUpperCase

str.toLocaleUpper()/str.toUpperCase() Convert string to uppercase

var str='My name is Dandan'

var str1=str.toLocaleUpperCase()

var str2=str.toUpperCase()

console.log(str1); // MY NAME IS DANDAN

console.log(str2); // MY NAME IS DANDAN

str.toString() returns the string form of the specified object 

var str='我是蛋蛋'

var str1=str.toString()

console.log(str1); // 我是蛋蛋

trimLeft

str.trimLeft() removes spaces on the left side of a string

trimRight

str.trimRight() removes spaces on the left side of the string

replacereplace

str.replace(str1,str2) Replace the matched string, str1 needs to match the string, str2 needs to replace the string, parameter 1 can be a regular expression and will not change the original string.

var str='My name is Dandan'

var str1=str.replace('Dandan','Lianlian')

var str2=str.replace(/Dandan/,'Lianlian')

console.log(str1); // My name is Lianlian

console.log(str2); // My name is Lianlian

regular expression

modifier

/xxx/g: Global modifier. By default, it will end when it encounters the first matching character. The g modifier allows it to match until the end.

/xxx/i: ignore case

/xxx/m: Matches multi-line text. By default, the regular expression stops when it encounters a newline character. It cannot match multi-line text.

escape character

\n (line feed), \r (carriage return), \t (tab), \w (any letter, number, or underscore), \W (any letter, number, or underscore) characters other than), \s (space), \S (non-space), \d (digits 0-9), \D (non-digit), \b (word boundary), \B (non-word boundary) , \\ (\ itself), . (any character except line feed and carriage return)

character set and

[]: or [abc] means matching a or b or c

Number: [/d], [/0-9]

Alphabet: [az], [AZ], [a-zA-Z]

Negation: ^ placed inside [] is negated, placed outside it starts with... [^abc] means any character except abc, ^[abc] means matching a string starting with a or b or c

character boundaries

$: Match the end abc$ means the match ends with abc

\b: The word boundary abc\b means that the string with abc as the boundary can match abc, but not abcc

quantifier

{n}: Match n times a{2} means match aa

{m,n}: Match m to n times, giving priority to matching n times a{1,3} means it can match aaa, aa, a

{m,}: Match m to unlimited times, priority is given to matching unlimited times.

? : Match 0 or 1 times, priority is given to matching 1 time, equivalent to {0,1}

+: Equivalent to {1,}

*: Equivalent to {0,}

Regularity has a greedy mode, and any two expressions indicating a range will be matched first. Add after the quantifier? You can turn on non-greedy mode and start matching with the following lines first.

Select expression

|: indicates grouping a|b indicates a or b, 123|456|789 indicates matching 123 or 456 and the latter 789

[] can only match a single character, | can match multiple characters

Grouping and referencing

(): The brackets are a group of (abc){2}, which means matching abcabc

Grouping cannot be placed inside [], but you can use | selection expression (123|456){2} to match 123123, 456456, 123456, 456123

Grouping is divided into capturing grouping and non-capturing grouping. The default is capturing. Adding ?: after the grouping ( can make the grouping non-capturing grouping. Non-capturing grouping can improve performance and simplify logic.

'123'.match(/(?123)/) returns ['123']

'123'.match(/(123)/) returns ['123','123']

Reference: \Number, the number indicates the previous capturing group to be referenced, non-capturing groups cannot be referenced

<([a-z]+)><\/\1> 表示匹配<span></span>、<div></div>

Regular expression method

test(): Retrieve the specified value in the string, return true or false

var pat=/my/ 

var str='my name is Danger!' 

console.log(pat.test(str)) // true

exec(): Retrieve the specified value in the string. The return value is the found value. If it is not found, it returns null.

var pat=/hello/ 
console.log(pat.exec('hello my name is Dange')) // 返回hello

search(): String search, the same as the method in the string API, returns the index if found, returns -1 if not found

match(): String matching, returning the found string in the form of an array

var str='1 plus 2 equal 3'

console.log(str.match(/\d+/)) // [1]

console.log(str.match(/\d+/g)) // [1,2,3]

Object methods

Object.is()

Strictly compare two values ​​for equality

let obj1 = { name: 'dandan' }
let obj = { name: 'dandan' }
let is = Object.is(obj, obj1)
let is1 = Object.is(obj, obj)
let is2 = Object.is(obj.name, obj1.name)
console.log(is); // false
console.log(is1); // true
console.log(is2); // true

Object.assign(obj1,obj2)

Merge objects. If obj1 has attributes, if obj2 does not, add them directly. If both have the attributes, the later ones will overwrite the previous ones.

let name = {
    name: 'dandan'
}
let age = {
    age: 18
}
let ass = Object.assign(name, age)
console.log(ass); // {name: 'dandan', age: 18}

Object.keys()

Traverse all key names of the object, only one level will be traversed

let person = {
    name: 'dandan',
    age: 18,
    hobby: ['听歌', '追剧'],
    family: {
        name: 'chen'
    }
}
let key = Object.keys(person)
console.log(key); // ['name', 'age', 'hobby', 'family']

Object.values()

Traverse all values ​​of the object, only one level will be traversed

let person = {
    name: 'dandan',
    age: 18,
    hobby: ['听歌', '追剧'],
    family: {
        name: 'chen'
    }
}
let value = Object.values(person)
console.log(value); // ['dandan', 18, ['听歌','追剧'], {name:'chen'}]

Object.entries()

Traverse all keys and values ​​of the object

let person = {
    name: 'dandan',
    age: 18,
    hobby: ['听歌', '追剧'],
    family: {
        name: 'chen'
    }
}
let entrie = Object.entries(person)
console.log(entrie); // [['name', 'dandan'],['age', 18],['hobby', ['听歌','追剧']],['family', {name:'chen'}]]

Object.fromEntries()

It is the inverse operation of entries. Its function is to convert an array of key-value pairs into an object.

// Object.fromEntries() 是entries的逆操作,作用是将一个键值对数组转化为一个对象
let entrie=[['name', 'dandan'],['age', 18],['hobby', ['听歌','追剧']],['family', {name:'chen'}]]
let from = Object.fromEntries(entrie)
console.log(from); // {name:'dandan',age:18,hobby:['听歌','追剧'],family:{name:'chen'}}

 If there are any omissions or errors, please correct me~

Guess you like

Origin blog.csdn.net/qq_44774622/article/details/132425113