001 页面导入样式时,使用 link 和@import 有什么区别?
002 用递归算法实现,数组长度为 5 且元素的随机数在 2-32 间不重复的值
function rand(arr = [], length = 5, min = 2, max = 32) {
if (arr.length < length) {
const num = Math.floor(Math.random() * (max - min + 1)) + min
if (!arr.includes(num)) {
arr.push(num)
}
return rand(arr)
}
return arr
}
003 去除字符串中的空格,根据传入不同的类型分别能去掉前、后、前后、中间的空格
const POSITION = Object.freeze({
left: Symbol(),
right: Symbol(),
both: Symbol(),
center: Symbol(),
all: Symbol()
})
function trim(str, position = POSITION.both) {
switch (position) {
case POSITION.left:
str = str.replace(/^\s+/, '')
break
case POSITION.right:
str = str.replace(/\s+$/, '')
break
case POSITION.both:
str = str.replace(/^\s+|\s+$/g, '')
break
case POSITION.center:
while (str.match(/\w\s+\w/)) {
str = str.replace(/(\w)(\s+)(\w)/, '$1$3')
}
break
case POSITION.all:
str = str.replace(/\s/g, '')
break
default:
break
}
return str
}
const str = ' s t r '
const result = trim(str, POSITION.left)
function delLast(str, char) {
if (!str) return false
if (!char) return str
const index = str.lastIndexOf(char)
return str.substring(0, index) + str.substring(index + 1)
}