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

九個超級有用的 Javascript 技巧

開發(fā) 前端
有時候前端需要對后端傳來的數(shù)據(jù)進行轉(zhuǎn)換以適應前端的業(yè)務邏輯,或者轉(zhuǎn)換組件的數(shù)據(jù)格式然后傳給后端處理,而 reduce 就是 一個非常強大的工具。

1. 動態(tài)加載 JS 文件

在一些特殊的場景下,尤其是在一些庫和框架的開發(fā)中,我們有時會動態(tài)加載并執(zhí)行 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. 實現(xiàn)模板引擎

以下示例使用很少的代碼來實現(xiàn)動態(tài)模板渲染引擎。它不僅支持普通動態(tài)變量的替換,還支持動態(tài) JS 語法邏輯包括 for 循環(huán)、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 轉(zhuǎn)換數(shù)據(jù)結構

有時候前端需要對后端傳來的數(shù)據(jù)進行轉(zhuǎn)換以適應前端的業(yè)務邏輯,或者轉(zhuǎn)換組件的數(shù)據(jù)格式然后傳給后端處理,而 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. 添加默認值

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

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 方法用于創(chuàng)建 NodeJS 原生 http 服務并監(jiān)聽端口,在服務的回調(diào)函數(shù)中創(chuàng)建上下文,然后調(diào)用用戶注冊的回調(diào)函數(shù)并傳遞生成的上下文。我們先看一下之前 createContext 和 handleRequest 的實現(xiàn)。

5. 該函數(shù)只執(zhí)行一次

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

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. 實現(xiàn) Curry

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

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. 實現(xiàn)單例模式

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

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. 實現(xiàn) CommonJs 規(guī)范

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

// 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 規(guī)范的簡單實現(xiàn)。核心解決了作用域的隔離,提供了 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
責任編輯:武曉燕 來源: 實戰(zhàn)案例錦集
相關推薦

2023-06-28 00:02:40

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開發(fā)功能

2022-12-19 15:23:51

JavaScrip開發(fā)語言

2023-08-18 15:12:00

JavaScript開發(fā)

2020-06-21 13:57:21

JavaScript開發(fā)代碼

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開發(fā)

2023-10-26 07:47:35

JavaScript代碼變量

2023-09-06 16:55:33

JavaScript閉包

2020-07-02 08:27:47

Javascript

2013-07-12 09:45:16

PHP功能

2023-05-18 15:32:02

HTML開發(fā)技巧

2024-02-26 08:20:00

CSS開發(fā)
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 91久久精品一区二区二区 | 国产精品日本一区二区在线播放 | 免费在线成人 | 久久中文免费视频 | 99国产精品久久久久久久 | 91精品国产综合久久婷婷香蕉 | 欧美性一区二区三区 | 日韩欧美中文字幕在线观看 | 久久久久国产精品午夜一区 | 中文字幕视频三区 | 久热精品免费 | 一级毛片播放 | 亚洲精品一区二区三区免 | 久久成人人人人精品欧 | 视频一区 亚洲 | 久久久亚洲一区 | 国内自拍第一页 | 亚洲精品一区二区冲田杏梨 | 成人在线播放网站 | 国产精品毛片av一区 | 免费黄色大片 | 亚洲久久一区 | 91精品国产91久久久久久丝袜 | 久久看精品 | 日韩久久精品 | 日本免费一区二区三区四区 | 91在线区| 亚洲综合色丁香婷婷六月图片 | 视频一区二区中文字幕 | 日韩国产三区 | 在线观看黄色电影 | 亚洲福利 | 韩日在线观看视频 | 日韩一区二区在线观看视频 | 欧美日本韩国一区二区 | 精品国产伦一区二区三区观看说明 | 日韩电影中文字幕 | 色婷婷综合久久久中字幕精品久久 | 欧美日韩亚洲视频 | 亚洲第一在线视频 | 精品国产欧美 |