Skip to content

用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值

javascript
function getVal(arr = [], index = 0, maxlen = 5) {
  if (arr.length === maxlen) return arr
  // Math.random 只会获取到 0 - 0.999999 的值
  const curVal = parseInt(Math.random() * (32 - 1) + 2, 10)
  if (arr.length === 0) return getVal([curVal])
  if (arr[index] === curVal) getVal(arr, index === arr.length - 1 ? index : ++index)
  arr.push(curVal)
  return getVal(arr)
}

写一个方法去掉字符串中的空格,要求传入不同的类型分别能去掉前、后、前后、中间的空格

javascript
function trim(str, type = "all") {
  var regexMap = {
    left: /^\s+/,
    right: /\s+$/,
    center: /(?<=\S)\s(?=\S)/g,
    both: /(^\s+)|(\s+$)/,
    all: /\s/g
  };
  var reg = regexMap[type];
  if (!reg) {
    throw new TypeError("type is invalid");
  }
  return str.replace(regexMap[type], "");
}

去除字符串中最后一个指定的字符

javascript
function delLast(str,target) {
  let reg =new RegExp(`${target}(?=([^${target}]*)$)`)
  return str.replace(reg,'')
}

function removeLastTxt(txt, target) {
  const len = txt.length
  const txts = txt.split('')
  let output = ''
  let isMatch = false
  for (let i = len - 1; i >= 0; i--) {
    if (txts[i] === target) {
      if (isMatch) {
        output = txts[i] + output
      } else {
        isMatch = true
      }
    } else {
      output = txts[i] + output
    }
  }
  return output
}

写一个方法把下划线命名转成大驼峰命名

javascript
function toCamel(str) {
  str = str.replace(/(\w)/, (match, $1) => `${$1.toUpperCase()}`)
  while(str.match(/\w_\w/)) {
    str = str.replace(/(\w)(_)(\w)/, (match, $1, $2, $3) => `${$1}${$3.toUpperCase()}`)
  }
  return str
}

function upperCase(str) {
  let isMatch = false
  const target = '_'
  return str.split('').reduce((acc, cur) => {
    if (cur === target) {
      isMatch = true
      return acc
    }
    if (isMatch) {
      isMatch = false
      return acc + cur.toUpperCase()
    }
    return acc + cur;
  }, '')
}

统计某一字符或字符串在另一个字符串中出现的次数

javascript
function getTotal(str, target) {
  const targetLen = target.length
  const targetArray = str.split('')
  return targetArray.reduce((acc, cur, curIndex) => {
    let temp = ''
    for (let i = 0; i <= targetLen - 1; i++) {
      temp += targetArray[i + curIndex]
    }
    if (temp === target) {
      return ++acc
    }
    return acc;
  }, 0)
}

const countSub = (str, sub) => str.split(sub).length - 1

写一个去除制表符和换行符的方法

javascript
const removeSymbol = (str) => str.replace(/\t|\n|\r|\f|\v/g, "");

写一个把字符串大小写切换的方法

javascript
function caseConvert(str) {
  return str.split('').map(s => {
    const code = s.charCodeAt();
    if (code < 65 || code > 122 || code > 90 && code < 97) return s;
    
    if (code <= 90) {
      return String.fromCharCode(code + 32)
    } else {
      return String.fromCharCode(code - 32)
    }
  }).join('')
}

具体原理:

a -> A 它的 chartCode 相差 32,利用这个规则,进行大小写切换

让一个数组乱序

javascript
function shuffle(array) {
  let _array = array.map(v => v)
  return array.reduce((acc, cur, curIndex, arr) => {
    // 取 [0, 数组长度 - 1] 的随机数
    const randomVal = Math.floor(Math.random() * _array.length)
    acc.push(
      _array[randomVal]
    )
    // 删除对应的数
    _array.splice(randomVal, 1)
    return acc
  }, [])
}

console.log(randomArray([0,1,2,3,4,5]))

上面这是洗牌算法

javascript
[1,2,3,4,5,6].sort(function(){
    return .5 - Math.random();
})

使用 sort 进行乱序,只要数据量不大,可保证一定的随机性

找到字符串中最长的单词

javascript
function getMaxLen(str) {
  const array = str.match(/\b[a-zA-Z]+\b/g)
  return array.reduce((acc, cur) => {
    if (cur.length > acc.length) return cur
    return acc
  }, '')
}

console.log(getMaxLen('sdfn hdo fjqw hqfweoubhr oiqwehuio rhqweouihr pqwep hpidofj jdfsdjfp ojep jfpej 134 5134 31 e geg dfg df g'))