javascript经典面试题:字体高亮函数

2018-02-0306:22:07WEB前端开发Comments2,815 views字数 552阅读模式

题目:请你完成 highlight 函数,可以把模版字符串中的插入内容替换掉,并且插入文档以后显示红色。例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html

const yourName = 'ScriptOJ'
const myName = 'Jerry'
document.body.innerHTML = highlight`Hello, ${yourName}. I am ${myName}.`

上面例子的页面显示如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html

0_1498033735172_upload-2abd65b1-1e98-46ba-b46f-df4188a036a5文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html

请你完成 highlight 函数的编写。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html

答案: css:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html

.highlight {
  color: red;
}

js:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html

// 考察的是 Tagged template literals 的使用
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const highlight = (strings, ...args) => {
  return strings.reduce((str, cur, i) => {
    return `${str}${cur}${args[i] ? `<span class="highlight">${args[i]}</span>` : '' }`
  }, '')
}
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/473.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/473.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定