成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

九個超級有用的 Javascript 技巧

開發 前端
在實際的開發工作過程中,我積累了一些常用的、超級有用的Javascript技巧和代碼片段,包括其他大神編譯的JS使用技巧。

前言

在實際的開發工作過程中,我積累了一些常用的、超級有用的Javascript技巧和代碼片段,包括其他大神編譯的JS使用技巧。

今天這篇文章,我認真篩選了9個我認為比較實用的技巧跟大家一起來分享,也歡迎你在留言區給我們留言,把你認為一些重要而有用的技巧與大家分享一下。

1.動態加載JS文件

在一些特殊的場景下,尤其是在一些庫和框架的開發中,我們有時會動態加載并執行JS文件。

下面是使用Promise的簡單封裝。

function loadJS(files, done) {
   // Get the head tag
   const head = document. getElementsByTagName('head')[0];
   Promise.all(files.map(file => {
     return new Promise(resolve => {
       // create script tag and add to head
       const s = document.createElement('script');
       s.type = "text/javascript";
       s.async = true;
       s.src = file;
       // Listen to the load event, resolve if the loading is complete
       s. addEventListener('load', (e) => resolve(), false);
       head.appendChild(s);
     });
   })).then(done); // everything is done, execute the user's callback event
}
loadJS(["test1.js", "test2.js"], () => {
   // user's callback logic
});There are two core points in the code above. One is to use Promise to process asynchronous logic, but to use script tags to load and execute js.

2. 實現模板引擎

以下示例使用很少的代碼來實現動態模板渲染引擎。它不僅支持普通動態變量的替換,還支持動態JS語法邏輯包括for循環、if判斷等。

// This is a dynamic template that contains js code
var template =
'My avorite sports:' +
'<%if(this.showSports) {%>' +
     '<% for(var index in this.sports) { %>' +
     '<a><%this.sports[index]%></a>' +
     '<%}%>' +
'<%} else {%>' +
     '<p>none</p>' +
'<%}%>';
// This is the function string we're going to concatenate
const code = `with(obj) {
   var r=[];
   r.push("My avorite sports:");
   if(this. showSports) {
     for(var index in this. sports) {
       r. push("<a>");
       r.push(this.sports[index]);
       r. push("</a>");
     }
   } else {
     r.push("<span>none</span>");
   }
   return r.join("");
}`
// dynamically rendered data
const options = {
   sports: ["swimming", "basketball", "football"],
   showSports: true
}
// Build a feasible function and pass in parameters to change the direction of this when the function is executed
result = new Function("obj", code).apply(options, [options]);
console. log(result);

3.使用reduce轉換數據結構

有時候前端需要對后端傳來的數據進行轉換以適應前端的業務邏輯,或者轉換組件的數據格式然后傳給后端處理,而reduce就是 一個非常強大的工具。

const arr = [
    { classId: "1", name: "Jack", age: 16 },
    { classId: "1", name: "Jon", age: 15 },
    { classId: "2", name: "Jenny", age: 16 },
    { classId: "3", name: "Jim", age: 15 },
    { classId: "2", name: "Zoe", age: 16 }
];
groupArrayByKey(arr, "classId");
function groupArrayByKey(arr = [], key) {
    return arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {})
}

很多復雜的邏輯如果通過reduce處理的話,就非常簡單了。

4.添加默認值

有時,方法需要用戶傳入參數。通常,我們有兩種方法來處理。如果用戶不傳入,我們通常會給出一個默認值,或者用戶必須傳入一個參數,不傳則拋出錯誤。

function double() {
     return value *2
}
// If not passed, give a default value of 0
function double(value = 0) {
     return value * 2
}
// The user must pass a parameter, and an error will be thrown if no parameter is passed
const required = () => {
     throw new Error("This function requires one parameter.")
}
function double(value = required()) {
     return value * 2
}
double(3) // 6
double() // throw Error

Listen方法用于創建NodeJS原生http服務并監聽端口,在服務的回調函數中創建上下文,然后調用用戶注冊的回調函數并傳遞生成的上下文。我們先看一下之前createContext和handleRequest的實現。

5.該函數只執行一次

在某些情況下,我們有一些特殊的場景,某個函數只允許執行一次,或者某個綁定方法只允許執行一次。

export function once (fn) {
   // Use the closure to determine whether the function has been executed
   let called = false
   return function () {
     if (! called) {
       called = true
       fn. apply(this, arguments)
     }
   }
}

6. 實現Curry

JavaScript 中的柯里化是將采用多個參數的函數轉換為一系列僅采用一個參數的函數的過程。這樣可以更靈活地使用函數,減少代碼的重復,提高代碼的可讀性。

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2));
      };
    }
  };
}
function add(x, y) {
  return x + y;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)); // output 3
console.log(curriedAdd(1, 2)); // output 3

通過柯里化,我們可以將一些常用的功能模塊化,比如驗證、緩存等。 這提高了代碼的可維護性和可讀性,并減少了出錯的機會。

7. 實現單例模式

JavaScript的單例模式是一種常用的設計模式。它可以確保一個類只有一個實例,并提供對該實例的全局訪問點。它在JS中有廣泛的應用場景,比如購物車、緩存對象、全局狀態管理等等。

let cache;
class A {
  // ...
}
function getInstance() {
  if (cache) return cache;
  return cache = new A();
}
const x = getInstance();
const y = getInstance();
console.log(x === y); // true

8. 實現CommonJs規范

CommonJS規范的核心思想是將每個文件視為一個模塊,每個模塊都有自己的作用域,其中的變量、函數和對象都是私有的,外部無法訪問。要訪問模塊中的數據,您必須導出并要求。

// id: full file name
const path = require('path');
const fs = require('fs');
function Module(id){
     // Used to uniquely identify the module
     this.id = id;
     // Properties and methods used to export modules
     this.exports = {};
}
function myRequire(filePath) {
     // Directly call the static method of Module to load the file
     return Module._load(filePath);
}
Module._cache = {};
Module._load = function(filePath) {
     // First address the absolute path of the file through the filePath passed in by the user
     // Because in CommnJS, the unique identifier of the module is the absolute path of the file
     const realPath = Module._resoleveFilename(filePath);
     // Cache priority, if it exists in the cache, it will directly return the exports property of the module
     let cacheModule = Module._cache[realPath];
     if(cacheModule) return cacheModule. exports;
     // If it is loaded for the first time, a new module is required, and the parameter is the absolute path of the file
     let module = new Module(realPath);
     // Call the load method of the module to compile the module
     module.load(realPath);
     return module. exports;
}
// The node file is not discussed yet
Module._extensions = {
    // Process the js file
   ".js": handleJS,
   // process the json file
   ".json": handleJSON
}
function handleJSON(module) {
  // If it is a json file, read it directly with fs.readFileSync,
  // Then use JSON.parse to convert and return directly
   const json = fs.readFileSync(module.id, 'utf-8')
   module.exports = JSON.parse(json)
}
function handleJS(module) {
   const js = fs. readFileSync(module. id, 'utf-8')
   let fn = new Function('exports', 'myRequire', 'module', '__filename', '__dirname', js)
   let exports = module. exports;
   // The assembled function can be executed directly
   fn.call(exports, exports, myRequire, module, module.id, path.dirname(module.id))
}
Module._resolveFilename = function (filePath) {
   // Splice the absolute path, and then search it, if it exists, it will return
   let absPath = path. resolve(__dirname, filePath);
   let exists = fs.existsSync(absPath);
   if (exists) return absPath;
   // If it does not exist, try splicing .js, .json, .node in sequence
   let keys = Object.keys(Module._extensions);
   for (let i = 0; i < keys. length; i++) {
     let currentPath = absPath + keys[i];
     if (fs.existsSync(currentPath)) return currentPath;
   }
};
Module.prototype.load = function(realPath) {
   // Get the file extension and hand it over to the corresponding method for processing
   let extname = path.extname(realPath)
   Module._extensions[extname](this)
}

以上是CommonJs規范的簡單實現。核心解決了作用域的隔離,提供了Myrequire方法來加載方法和屬性。

9. 遞歸獲取對象屬性

如果讓我選擇使用最廣泛的設計模式,我會選擇觀察者模式。如果要選我遇到過最多的算法思維,那一定是遞歸。遞歸將原問題劃分為具有相同結構的結構。子問題,然后依次解決這些子問題,并結合子問題的結果,最終得到原問題的答案。

const user = {
   info: {
     name: "Jacky",
     address: { home: "MLB", company: "AI" },
   },
};
// obj is the object to get the property, path is the path, and fallback is the default value
function get(obj, path, fallback) {
   const parts = path. split(".");
   const key = parts. shift();
   if (typeof obj[key] !== "undefined") {
     return parts. length > 0 ?
       get(obj[key], parts. join("."), fallback) :
       obj[key];
   }
   // return fallback if key not found
   return fallback;
}
console.log(get(user, "info.name")); // Jacky
console.log(get(user, "info.address.home")); // MLB
console.log(get(user, "info.address.company")); // AI
console.log(get(user, "info.address.abc", "fallback")); // fallback

總結

以上就是我今天為大家精選的全部內容,也是我認為比較有用的9個JavaScript技巧,希望對大家有所幫助

責任編輯:華軒 來源: web前端開發
相關推薦

2023-07-18 07:56:31

工具reduce業務

2022-12-25 16:03:31

JavaScript技巧

2022-12-22 14:44:06

JavaScript技巧

2022-11-07 16:25:07

JavaScript技巧

2023-08-11 17:39:43

JavaScriptWeb 應用程序

2023-05-30 15:11:16

JavaScrip開發功能

2022-12-19 15:23:51

JavaScrip開發語言

2023-08-18 15:12:00

JavaScript開發

2020-06-21 13:57:21

JavaScript開發代碼

2023-09-07 16:28:46

JavaScrip

2022-05-30 09:44:11

TypeScriptJavaScript技巧

2011-07-15 10:02:01

JavaScript

2023-05-28 23:23:44

2024-08-20 15:23:27

JavaScript開發

2023-10-26 07:47:35

JavaScript代碼變量

2023-09-06 16:55:33

JavaScript閉包

2023-05-18 15:32:02

HTML開發技巧

2013-07-12 09:45:16

PHP功能

2020-07-02 08:27:47

Javascript

2024-02-26 08:20:00

CSS開發
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产麻豆乱码精品一区二区三区 | 日本成人三级电影 | 无码日韩精品一区二区免费 | 久操国产| 四虎影视免费在线 | 人人人人人爽 | 日韩二| 国产伦精品一区二区三区高清 | 久久精品欧美一区二区三区不卡 | 99亚洲精品 | 精品久久久久久18免费网站 | 欧美日韩淫片 | 亚洲精品一区av在线播放 | 99精品一区二区三区 | 成人亚洲综合 | 国产视频在线观看一区二区三区 | 91丨九色丨国产在线 | 草久视频| 久久精品国产一区二区三区不卡 | 国产精品久久久久久久久免费桃花 | 精品在线观看一区 | 第四色播日韩第一页 | 日日日日操 | 91免费观看国产 | 在线观看亚洲欧美 | 有码在线 | 久久中文字幕一区 | 成人h动漫亚洲一区二区 | 久久久亚洲一区 | 日韩中文字幕在线观看 | 羞羞网站在线观看 | 一区二区三区在线观看视频 | 国产精品免费一区二区 | 日本精品久久 | 日本午夜网站 | 国产精品99久久久久久久久久久久 | 国产欧美日韩在线播放 | 亚洲天堂中文字幕 | 欧美精品一区二区在线观看 | www国产成人免费观看视频,深夜成人网 | 国产高清在线精品 |