全能編程開發工程師手冊

作為一名全能編程開發工程師,需要掌握多種編程語言和技術棧,並且在開發過程中需要處理各種問題和bug。以下是一些常用的code snippet,能夠幫助工程師們更好地完成開發任務。

一、字符串操作

1. 獲取字符串長度


const str = "Hello World!";
const len = str.length;
console.log(len); // 12

使用JavaScript中的 .length方法即可獲取字符串的長度。

2. 字符串截取


const str = "Hello World!";
const substr = str.substring(0, 5);
console.log(substr); // "Hello"

使用JavaScript中的 .substring()方法進行字符串截取操作,第一個參數為起始位置,第二個參數為結束位置(不包括該位置)。

3. 字符串替換


const str = "Hello World!";
const strReplace = str.replace("Hello", "Hi");
console.log(strReplace); // "Hi World!"

使用JavaScript中的 .replace()方法進行字符串替換操作,第一個參數為被替換內容,第二個參數為替換內容。

二、數組操作

1. 數組添加元素


const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]

使用JavaScript中的 .push()方法進行數組添加操作,將元素添加至數組末尾。

2. 數組截取


const arr = [1, 2, 3];
const subArr = arr.slice(0, 2);
console.log(subArr); // [1, 2]

使用JavaScript中的 .slice()方法進行數組截取操作,第一個參數為起始位置,第二個參數為結束位置(不包括該位置)。

3. 數組去重


const arr = [1, 2, 2, 3, 3, 3];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3]

使用ES6中的Set對象對數組進行去重操作,然後通過 Array.from()方法將Set對象轉化為數組。

三、邏輯操作

1. 判斷一個值是否在數組中


const arr = [1, 2, 3];
const isIncluded = arr.includes(2);
console.log(isIncluded); // true

使用JavaScript中的 .includes()方法進行判斷操作,返回布爾值。

2. 判斷一個值是否為空或undefined


const value = null;
if (!value) {
  console.log("value is empty or undefined");
}

通過 !運算符,判斷值是否為空或undefined。

3. 判斷對象是否為空


const obj = {};
const objIsEmpty = Object.keys(obj).length === 0 && obj.constructor === Object;
console.log(objIsEmpty); // true

通過判斷對象的鍵的數量和類型,來判斷對象是否為空。

四、網絡操作

1. 使用fetch進行網絡請求


fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data));

使用JavaScript中的fetch函數進行網絡請求操作,返回一個Promise對象。

2. 使用Axios進行網絡請求


axios.get("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => console.log(response.data));

使用第三方庫Axios進行網絡請求操作,在使用前需要先進行引入。

3. 下載文件


const downloadFile = (url, fileName) => {
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  a.click();
}

通過創建一個a標籤的方式,設置鏈接和文件名,觸發點擊操作來下載文件。

原創文章,作者:MJTEP,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/351714.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
MJTEP的頭像MJTEP
上一篇 2025-02-17 17:02
下一篇 2025-02-17 17:02

相關推薦

發表回復

登錄後才能評論