JS中的高級方法


1:Object.assign()
把source對象中所有可枚舉的屬性copy到target對象中。 可以用來合並兩個對象的屬性。

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

2:Object.getOwnPropertyNames()
以數組形式返回對象所有屬性的名稱


const object1 = {
  a: 1,
  b: 2,
  c: 3
};

console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

3:Object.keys(),Object.values(),Object.entries()
Object.keys方法,返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵名。

var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)
// ["foo", "baz"]

Object.values方法返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值。

const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]

Object.entries()方法返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值對數組。


const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

4:結構

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }

5:鏈判斷運算符

// 錯誤的寫法
const  firstName = message.body.user.firstName;

// 正確的寫法
const firstName = (message
  && message.body
  && message.body.user
  && message.body.user.firstName) || 'default';

//這樣的層層判斷非常麻煩,因此 ES2020 引入了“鏈判斷運算符”(optional chaining operator)?.,簡化上面的寫法。
const firstName = message?.body?.user?.firstName || 'default';
const fooValue = myForm.querySelector('input[name=foo]')?.value

參考:https://es6.ruanyifeng.com/#docs/object

6:Symbol
實例 - 消除魔術字符
改造前

function getArea(shape, options) {
  let area = 0;

  switch (shape) {
    case 'Triangle': // 魔術字符串
      area = .5 * options.width * options.height;
      break;
    /* ... more code ... */
  }

  return area;
}

getArea('Triangle', { width: 100, height: 100 }); // 魔術字符串

改造后


const shapeType = {
  triangle: Symbol()  //這里為什么不用triangle: 'Triangle'來表示?  因為這里triangle只是一個標識,具體是什么值不重要,所以用Symbol最合適
};

function getArea(shape, options) {
  let area = 0;
  switch (shape) {
    case shapeType.triangle:
      area = .5 * options.width * options.height;
      break;
  }
  return area;
}

getArea(shapeType.triangle, { width: 100, height: 100 });

Symbol 作為屬性名,遍歷對象的時候,該屬性不會出現在for...in、for...of循環中,也不會被Object.keys()、Object.getOwnPropertyNames()、JSON.stringify()返回。
Object.getOwnPropertySymbols()方法,可以獲取指定對象的所有 Symbol 屬性名。該方法返回一個數組,成員是當前對象的所有用作屬性名的 Symbol 值。

const obj = {};
let a = Symbol('a');
let b = Symbol('b');

obj[a] = 'Hello';
obj[b] = 'World';

const objectSymbols = Object.getOwnPropertySymbols(obj);

objectSymbols
// [Symbol(a), Symbol(b)]

參考:https://es6.ruanyifeng.com/#docs/symbol

7: 標簽函數 - tag function

var person = 'Mike';
var age = 28;
​
function myTag(strings, personExp, ageExp) {
​
  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "
​
  // There is technically a string after
  // the final expression (in our example),
  // but it is empty (""), so disregard.
  // var str2 = strings[2];
​
  var ageStr;
  if (ageExp > 99){
    ageStr = 'centenarian';
  } else {
    ageStr = 'youngster';
  }
​
  return str0 + personExp + str1 + ageStr;
​
}
​
var output = myTag`that ${ person } is a ${ age }`;
​
console.log(output);
//輸出字符串that Mike is a youngster

console命令打印出標簽中的內容

console.log `aaa${1}bbb`
//['aaa','bbb'] 1
console.log `aaa${1}b${2}bb`
//['aaa','b','bb'] 1 2

styled-components就是一個典型的標簽函數的應用。


免責聲明!

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



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