處理JS中undefined的7個技巧


typeof undefined === "undefined"; // => true

let nothing; typeof nothing === "undefined"; // => true

 

檢查屬性是否存在:

JS 提供了許多方法來確定對象是否具有特定屬性:

1.obj.prop != undefined 直接和undefined比較

2.typeof obj.prop != 'undefined' 驗證屬性值類型

3.obj.hasOwnProperty('prop'):驗證對象是否具有自己的屬性

4.'prop' in obj 驗證對象是否具有自己的屬性或繼承屬性

解構訪問對象屬性:

const object = { }; const { prop = 'default' } = object;

prop; // => 'default'

function quote(str, { char = '"', skipIfQuoted = true } = {}) {
  const length = str.length;
  if (skipIfQuoted
      && str[0] === char
      && str[length - 1] === char) {
    return str;
  }
  return char + str + char;
}
quote('Hello World', { char: '*' }); // => '*Hello World*'
quote('Sunny day');                  // => '"Sunny day"'

={}在解構賦值的右側,確保在完全沒有指定第二個參數的情況下使用空對象。

用默認屬性填充對象

ES6 Object.assign(target,source1,source2,...)將所有可枚舉的自有屬性的值從一個或多個源對象復制到目標對象中,該函數返回目標對象。

枚舉源對象的順序很重要:后面的源對象屬性會覆蓋前面的源對象屬性。const unsafeOptions = {
  fontSize: 18
};
const defaults = {
  fontSize: 16,
  color: 'black'
};
const options = Object.assign({}, defaults, unsafeOptions);
options.fontSize; // => 18
options.color;    // => 'black'
const unsafeOptions = {
  fontSize: 18
};
const defaults = {
  fontSize: 16,
  color: 'black'
};
const options = {
  ...defaults,
  ...unsafeOptions
};
options.fontSize; // => 18
options.color;    // => 'black'

使用默認參數值

function multiply(a, b) {
  if (b === undefined) {
    b = 2;
  }
  a; // => 5
  b; // => 2
  return a * b;
}
multiply(5); // => 10
雖然所提供的分配默認值的方法有效,但不建議直接與undefined值進行比較。它很冗長,看起來像一個hack .

這里可以使用 ES6 的默認值:

function multiply(a, b = 2) {
  a; // => 5
  b; // => 2
  return a * b;
}
multiply(5);            // => 10
multiply(5, undefined); // => 10 

 函數返回值

function square(x) {
  const res = x * x;
}
square(2); // => undefined  
square() 函數沒有返回計算結果,函數調用時的結果undefined。

當return語句后面沒有表達式時,默認返回 undefined。

function square(x) {
  const res = x * x;
  return;
}
square(2); // => undefined
return; 語句被執行,但它不返回任何表達式,調用結果也是undefined。

function square(x) {
  const res = x * x;
  return res;
}
square(2); // => 4

不要相信自動插入分號

當換行符位於returnreturn \n expression之間時,ASI 會在換行符之前自動插入分號(return; \n expression)。

function getPrimeNumbers() {
  return 
    [ 2, 3, 5, 7, 11, 13, 17 ]
}
getPrimeNumbers() // => undefined
在return語句和數組之間存在一個換行,JS 在return后自動插入分號,解釋代碼如下:

function getPrimeNumbers() {
  return; 
  [ 2, 3, 5, 7, 11, 13, 17 ];
}
getPrimeNumbers(); // => undefined
return; 使函數getPrimeNumbers() 返回undefined而不是期望的數組。

這個問題通過刪除return和數組文字之間的換行來解決:

function getPrimeNumbers() {
  return [ 
    2, 3, 5, 7, 11, 13, 17 
  ];
}
getPrimeNumbers(); // => [2, 3, 5, 7, 11, 13, 17]

void 操作符

void <expression>計算表達式無論計算結果如何都返回undefined 。

void 1; // => undefined void (false); // => undefined void {name: 'John Smith'}; // => undefined void Math.min(1, 3); // => undefined

總結

undefined的存在是JS的允許性質的結果,它允許使用:

  • 未初始化的變量
  • 不存在的對象屬性或方法
  • 訪問越界索引的數組元素
  • 不返回任何結果的函數的調用結果

大多數情況下直接與undefined進行比較是一種不好的做法。一個有效的策略是減少代碼中undefined關鍵字的出現:

  • 減少未初始化變量的使用
  • 使變量生命周期變短並接近其使用的位置
  • 盡可能為變量分配初始值
  • 多敷衍 const 和 let
  • 使用默認值來表示無關緊要的函數參數
  • 驗證屬性是否存在或使用默認屬性填充不安全對象
  • 避免使用稀疏數組

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM