您现在的位置是:亿华云 > 应用开发

你可能会用到的JS工具函数

亿华云2025-10-03 22:08:18【应用开发】8人已围观

简介Vue3在script标签中引入constoDiv=document.createElement(div);constoScript=document.createElement(script);oD

Vue3在script标签中引入

const oDiv = document.createElement(div);     const oScript = document.createElement(script);     oDiv.setAttribute(id,用函数 app);     oScript.type = text/javascript;     oScript.src = "https://unpkg.com/vue@next";     document.body.appendChild(oDiv);     document.body.appendChild(oScript);     window.onload = function () {        const {  createApp,ref } = Vue;       const App = {          template: `             <div>{ { msg}}</div>             <p>{ { count}}</p>             `,         data(){                return {                  msg:maomin               }         },         setup(){            let count = ref(0);           return {              count           }         }     }      createApp(App).mount(#app);     } 

递归寻找操作(已删除指定项为例)

// 递归寻找     recursion(data, id) {        let result;       if (!data) {          return;       }       for (let i = 0; i < data.length; i++) {          let item = data[i];         if (item.breakerId === id) {            result = item;           data.splice(i, 1);           break;         } else if (item.childrenBranch && item.childrenBranch.length > 0) {            result = this.recursion(item.childrenBranch, id);           if (result) {              return result;           }         }       }       return result;     }, 

递归数组,将数组为空设为undefined

function useTree(data) {         for (let index = 0; index < data.length; index++) {           const element = data[index];          if (element.childrenBranch.length < 1) {             element.childrenBranch = undefined;          } else {             useTree(element.childrenBranch);          }        }        return data;      } 

数组对象中相同属性值的工具个数

group(arr) {        var obj = { };       if (Array.isArray(arr)) {          for (var i = 0; i < arr.length; ++i) {            var isNew = arr[i].isNew;           if (isNew in obj) obj[isNew].push(arr[i]);           else obj[isNew] = [arr[i]];         }       }       return obj;     },     max(obj) {        var ret = 0;       if (obj && typeof obj === "object") {          for (var key in obj) {            var length = obj[key].length;           if (length > ret) ret = length;         }       }       return ret;     }, var data = [     {       addr: "1",      isNew: false,     },     {       addr: "2",      isNew: false,     } ] max(group(data) // 2 

检测版本是云南idc服务商vue3

import {  h } from vue; const isVue3 = typeof h === function; console.log(isVue3) 

检测数据对象中是否有空对象

let arr = [{ },{ name:1}] const arr = this.bannerList.filter(item =>        item == null || item ==  || JSON.stringify(item) == { } );  console.log(arr.length > 0 ? 不通过 : 通过) 

深拷贝

 /* @param { *} obj  * @param { Array<Object>} cache  * @return { *}  */ function deepCopy (obj, cache = []) {    // just return if obj is immutable value   if (obj === null || typeof obj !== object) {      return obj   }   // if obj is hit, it is in circular structure   const hit = find(cache, c => c.original === obj)   if (hit) {      return hit.copy   }   const copy = Array.isArray(obj) ? [] : { }   // put the copy into cache at first   // because we want to refer it in recursive deepCopy   cache.push({      original: obj,     copy   })   Object.keys(obj).forEach(key => {      copy[key] = deepCopy(obj[key], cache)   })   return copy } const objs = {      name:maomin,     age:17 } console.log(deepCopy(objs)); 

h5文字转语音

speech(txt){      var synth = null;     var msg = null;     synth = window.speechSynthesis;     msg = new SpeechSynthesisUtterance();     msg.text = txt;     msg.lang = "zh-CN";     synth.speak(msg);     if(window.speechSynthesis.speaking){        console.log("音效有效");      } else {       console.log("音效失效");      }  } 

模糊搜索

recursion(data, name) {              let result;             if (!data) {                  return;             }             for (var i = 0; i < data.length; i++) {                  let item = data[i];                 if (item.name.toLowerCase().indexOf(name) > -1) {                      result = item;                     break;                 } else if (item.children && item.children.length > 0) {                      result = this.recursion(item.children, name);                     if (result) {                          return result;                     }                 }             }             return result;         },         onSearch(v) {              if (v) {                  if (!this.recursion(this.subtable, v)) {                      this.$message({                          type: error,                         message: 搜索不到,                     });                 } else {                      this.tableData = [this.recursion(this.subtable, v)];                 }             }         }, 

input 数字类型

  <el-input                    v-model.number="form.redVal"                    type="number"                    @keydown.native="channelInputLimit"                    placeholder="请输入阈值设定"                    maxlength="8" ></el-input>    channelInputLimit(e) {         let key = e.key;        // 不允许输入‘e‘和‘.‘        if (key === e || key === .) {             e.returnValue = false;            return false;        }        return true;    }, 

排序(交换位置)

const list = [1,2,3,4,5,6];     function useChangeSort (arr,oldIndex,newIndex){          const targetRow = arr.splice(oldIndex, 1)[0];         const targetRow1 = arr.splice(newIndex, 1)[0];         arr.splice(newIndex, 0, targetRow);         arr.splice(oldIndex, 0, targetRow1);         return arr     }     console.log(useChangeSort(list,5,0)); // [6, 2, 3, 4, 5, 1] 

格式化时间

/**  * Parse the time to string  * @param { (Object|string|number)} time  * @param { string} cFormat  * @returns { string | null}  */ export function parseTime(time, cFormat) {      if (arguments.length === 0 || !time) {          return null;     }     const format = cFormat || { y}-{ m}-{ d} { h}:{ i}:{ s};     let date;     if (typeof time === object) {          date = time;     } else {          if (typeof time === string) {              if (/^[0-9]+$/.test(time)) {                  // support "1548221490638"                 time = parseInt(time);             } else {                  // support safari                 // https://stackoverflow.com/questions/4310953/invalid-date-in-safari                 time = time.replace(new RegExp(/-/gm), /);             }         }         if (typeof time === number && time.toString().length === 10) {              time = time * 1000;         }         date = new Date(time);     }     const formatObj = {          y: date.getFullYear(),         m: date.getMonth() + 1,         d: date.getDate(),         h: date.getHours(),         i: date.getMinutes(),         s: date.getSeconds(),         a: date.getDay()     };     const time_str = format.replace(/{ ([ymdhisa])+}/g, (result, key) => {          const value = formatObj[key];         // Note: getDay() returns 0 on Sunday         if (key === a) {              return [日, 一, 二, 三, 四, 五, 六][value];         }         return value.toString().padStart(2, 0);     });     return time_str; } 

本文转载自微信公众号「前端历劫之路」,亿华云计算可以通过以下二维码关注。用函数转载本文请联系前端历劫之路公众号。源码下载工具

用函数

用函数

很赞哦!(47512)