huaTJ0210 / fe-interview-questions-collect

MIT License
0 stars 0 forks source link

javascript!! 面试题汇总 #6

Open huaTJ0210 opened 1 year ago

huaTJ0210 commented 1 year ago

javascript相关面试题汇总

huaTJ0210 commented 1 year ago

1、检验给出的字符串 <div><span>text</span></div> 是否为合法的html文本

function isValideHtmlText(text) {
  // 1、获取文本中所有的开始和结束标签
  const arrayOfHtmlText = text.match(/<[^<>]+>/g)

  // 2、遍历数组,对开始标签进行压栈处理,遇到结束标签且匹配栈顶元素则进行出栈处理,不匹配则直接返回false
  const stack = []
  for (let index = 0; index < arrayOfHtmlText.length; index++) {
    const item = arrayOfHtmlText[index]
    if (isStartTag(item)) {
      stack.push(item)
    } else if (isEndTag(item)) {
      const cur = stack[stack.length - 1]
      if (cur === item.replace(/\//, '')) {
        stack.pop()
      } else {
        return false
      }
    }
  }
  // 栈为空则证明是合法的
  return stack.length === 0
}

function isEndTag(tag) {
  return tag.includes('/')
}
function isStartTag(tag) {
  return !tag.includes('/')
}

//  ===== 测试 ===

const text = `<div>123<p>123</p></div>`
console.log(isValideHtmlText(text)) // true

const text1 = `<div><p>123</p><span></div>`
console.log(isValideHtmlText(text1)) // false
huaTJ0210 commented 1 year ago

2、Promise

需要了解Promise的知识点: