JavaScript的一些常用函数

//生成随机颜色

const Color = () => `#${
      
      Math.floor(Math.random() * 0xffffff).toString(16)}`
console.log(Color ())

// 复制文字到剪切板

const copyToClipboard = 
(text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard("Hello World!")

// 获取url参数

const getParamUrl = (key) => {
    
    
  const url = new URL(location.href)
  return url.searchParams.get(key)
}

// 滚动到底部

const scrollToBottom = (element) => 
  element.scrollIntoView({
    
     behavior: "smooth", block: "end" });

// 滚动到顶部

const scrollToTop = (element) => 
  element.scrollIntoView({
    
     behavior: "smooth", block: "start" });

// 数组随机排序,音乐播放器随机播放登会用到洗牌算法

// sort重排序
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5)
const arr = [1, 2, 3, 4, 5]
console.log(shuffle(arr))

// 洗牌算法重排序
function shuffle2(array){
    
    
    let result = [], random;
    while(array.length>0){
    
    
        random = Math.floor(Math.random()*array.length);
        result.push(array[random]);
        array.splice(random, 1);
    }
    return result;
}
console.log(shuffle2(arr))

 function shuttle3(array) {
    
    
      for (i = array.length - 1; i >= 0; i--) {
    
    
           let random = Math.floor(Math.random() * (i))
           let ele= array[random]
           array[random] = array[i]
           array[i] = ele
       }
       return array
   }

猜你喜欢

转载自blog.csdn.net/Jonn1124/article/details/132743369