【代码】JS解题

1、删除字符串中出现次数最少的字符

function charcount(line) {
  var obj = {}
  var linelist = line.split('')
  linelist.forEach(item => {
    if (obj[item]) {
      obj[item]++
    } else {
      obj[item] = 1
    }
  })
  var objval = Object.values(obj).sort()
  var min = objval[0]
  for (var k in obj) {
    if (obj[k] <= min) {
      var reg = new RegExp(k, 'g')
      line = line.replace(reg, '')
    }
    // if (obj[k] <= min) {
    //   linelist = linelist.filter(item => item !== k)
    //   line = linelist.join('')
    // }
  }
  console.log(line)
}

const a = 'aaabbcdd'

charcount(a) // log: aaabbdd

2、代码输出顺序

async function async1() {
  console.log('async1 start')
  await async2()
  console.log('async1 end')
}
async function async2() {
  console.log('async2')
}
console.log('script start')
setTimeout(function() {
  console.log('setTimeout')
}, 0)
async1()
new Promise(function(resolve) {
  console.log('promise1')
  resolve()
  console.log('promise2')
}).then(function() {
  console.log('promise3')
})
console.log('script end')

/**
 * script start
 * async1 start
 * async2
 * promise1
 * promise2
 * script end
 * async1 end
 * promise3
 * setTimeout
 */

3、找出两个字符串中首个不重复的字符

const a = 'ababcbdsa'
const b = 'abcdefg'
let firstList = []
let secondList = []
if (a.length < b.length) {
  firstList = a.split('')
  secondList = b.split('')
} else {
  firstList = b.split('')
  secondList = a.split('')
}

function fun() {
  for (let i = 0; i < firstList.length; i++) {
    if (!secondList.includes(firstList[i])) {
      return firstList[i]
    }
  }
}

const c = fun()
console.log(c) // e

你可能感兴趣的:(javascript,html,前端)