具有多个可选参数的功能的控制台输出

具有多个参数的功能的控制台输出

我有这个类的方法:

searchForProduct({productName, manufacturer, seller}, itemsPerPage = 20, onlyAvailable = true) {
    console.log(Searching for...) // Here's what is my question about
    //do stuff
}

如何打印要传递给该方法的所有参数?

一个想要实现的目标是:

searchForProduct({productName: laptop});

// Output:
"Searching for productName: 'laptop'"

// or

searchForProduct({productName: "laptop", manufacturer: "Dell"});

// Output:
"Searching for productName: 'laptop', manufacturer: 'Dell'"

等等...

Also (if it's possible with any approach that will be proposed) I don't want to print out default itemsPerPage and onlyAvailable even if it will be passed to the method.

评论
nquis
nquis

我不会破坏第一个参数-而是对其进行字符串化或对其条目进行迭代以提取其键和值:

const searchForProduct = (obj) => {
  console.log('Searching for', JSON.stringify(obj));
};
searchForProduct({productName: 'laptop'});
searchForProduct({productName: "laptop", manufacturer: "Dell"});
const searchForProduct = (obj) => {
  const displayStr = Object.entries(obj)
    .map(([key, val]) => key + ': ' + val)
    .join(', ');
  console.log('Searching for', displayStr);
};
searchForProduct({productName: 'laptop'});
searchForProduct({productName: "laptop", manufacturer: "Dell"});
点赞
评论
笑回首
笑回首
如何打印要传递给该方法的所有参数?

它更像您希望看到第一个参数的对象属性

function searchForProduct(data, itemsPerPage = 20, onlyAvailable = true) {
  console.log(`Searching for ${JSON.stringify(Object.entries(data))}`)
}

criteria = {
  productName: '',
  manufacturer: ''
}

searchForProduct(criteria)
点赞
评论