[ES6] Function Params

本文介绍如何通过使用默认参数和命名参数来改进JavaScript函数定义,包括修复displayTopicsPreview函数的错误调用,完善setPageThread函数签名,以及重构loadProfiles函数以提高代码的可读性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Default Value of function param:

The function displayTopicsPreview() raises an error on the very first line when called with no arguments. Let's fix that!

function displayTopicsPreview( topics ){
  var message = "There are currently " + topics.length;
  _displayPreviewMessage(topics, message);
}

-----------------

function displayTopicsPreview( topics = [] ){
  let message = "There are currently " + topics.length;
  _displayPreviewMessage(topics, message);
}

 

2. Complete the setPageThread() function signature with the missing named parameters. You can check out the body of the function to help discover what options are expected.

function setPageThread(name,  ){
  let nameElement = _buildNameElement(name);
  let settings = _parseSettings(popular, expires, activeClass);

  _updateThreadElement(nameElement, settings);
}

-------------------

function setPageThread(name,  {popular, expires, activeClass}){
  let nameElement = _buildNameElement(name);
  let settings = _parseSettings(popular, expires, activeClass);

  _updateThreadElement(nameElement, settings);
}

 

3. Let's refactor the loadProfiles() function to use named parameters with default values.

function loadProfiles(userNames = [], options = {}) {
  let profilesClass = options.profilesClass || ".user-profile";
  let reverseSort   = options.reverseSort   || false;

  if (reverseSort) {
    userNames = _reverse(userNames);
  }

  _loadProfilesToSideBar(userNames, profilesClass);
}

------------------------------

function loadProfiles(userNames = [], {profilesClass, reverseSort} = {}) {
  profilesClass = profilesClass || ".user-profile";
  reverseSort   = reverseSort   || false;

  if (reverseSort) {
    userNames = _reverse(userNames);
  }

  _loadProfilesToSideBar(userNames, profilesClass);
}

 

function setPageThread(name, {popular, expires, activeClass} = {}){
  // ...
}

setPageThread("ES2015", {
    popular: true
}); 

//won't cause error

 

Important to take away from here is 

  • Instead of giving options = {} in the function param, we give {profileClass, reserseSort} = {}
  • First it is more clear to see what "options" it is
  • Second we assign default param here.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值