关于javascript:js一些方法记录

34次阅读

共计 1503 个字符,预计需要花费 4 分钟才能阅读完成。

1. 获取字符串中的元音

getYuan (str) {let arr = str.match(/[aeiou]/gi)
  return arr
}

2. 将带 #的字符串非凡解决

 parseComments (value) {
      var exp
      exp = /(#|#)((?!#).)*(#|#)/g
      value = value.replace(/<[^>]*?>(.*?)/gi, '').replace(/(.*?)<\/[^>]*?>/gi,'').replace(exp, (item) => {
        let newVal = '<span class="text-blue">' + item + '</span>'
        return newVal
      })
      return value
    }

3. 平方每个数

this.squareNum(9119)
squareNum (str) {// let strArr = (str + '').split(' ')
      // console.log(strArr)
      // let content = strArr.map((item) => {//   return Number(item) * Number(item)
      // }).join(' ')
      // console.log('content', content)
      let strArr = (str + '').split('')
      let content = strArr.map((item) => {return Number(item) * Number(item)
      }).join('')
      return content
    }

3.
console.log(‘is2’, ‘is2’.replace(/1/gi, ”)) // 2; 去掉字符串的非数字
console.log(‘sdf34’, ‘sdf34’.replace(/\d/g, ”)) // sdf; 去掉数字

4. 数组的深拷贝
(1) slice 办法复制数组

let copy = [1, 2, 3]
let deepCopy = copy.slice()
copy[2] = 4
console.log('copy', copy) // [1,2,4]
console.log('deepCopy', deepCopy) // [1,2,3]

(2) concat 办法复制数组

let copy = [1, 2, 3]
let deepCopy = [].concat(copy)
copy[2] = 4
console.log('copy', copy) // [1,2,4]
console.log('deepCopy', deepCopy) // [1,2,3]

(3) 遍历数组

forEach 或者 for 循环 

(4) 扩大运算符 办法复制数组

let copy = [1, 2, 3]
let deepCopy = [...copy]
copy[2] = 4
console.log('copy', copy)
console.log('deepCopy', deepCopy)

(5) 转换成 json 再转换成对象

let copy = [1, 2, 3]
let deepCopy = JSON.parse(JSON.stringify(copy))
copy[2] = 4
console.log('copy', copy)
console.log('deepCopy', deepCopy)

5. 对象的深拷贝
(1) for 循环

let copy = {
  name: 'xiaoyingzi',
  sex: 'female',
  age: 25
}
let res = {}
for (let i in copy) {console.log('i=====', i)
  res[i] = copy[i]
}
console.log('res', res) 
copy.name = 'xiaoyouzi'
console.log('res', res)

(2) 转换成 json 再转换成对象


  1. 0-9 ↩

正文完
 0