【发布时间】:2018-04-11 21:39:44
【问题描述】:
所以我们的代码中到处都是这些废话,IMO 太多了。例如:
const profileId = _.get(account, 'profileId', null);
const player = _.get(someCustomObject, 'player'); // Why?????? why not just someCustomObject.player?
当您可以通过对象访问对象属性时,对所有事情都使用 lodash 是我还是荒谬!一般来说,我们使用的是 lodash,它在很多地方都显得过于矫枉过正,并且使代码更加冗长且难以阅读。
在这种情况下,我们也不需要 lodash:
const profileId = _.get(account, 'profileId', null);
如果没有 lodash,有什么方法可以做到这一点?那是我的问题。以下是一些想法:
const profileId = (account && account.profileId) || null
还有其他想法吗?
更新
有趣的是,与 Ori 的答案一致,但在这里只是一个观察。我想删除默认 profileId 为 null 只是因为我觉得没有必要。但是为什么不把profileId设置为account对象呢?
const account = {};
const game = { player: 'Sam' }
console.log(`account: ${account}`);
const { profileId } = account || {};
const { player } = game || {};
console.log(`profileId: ${profileId} // why is this undefined if account has value {}???`);
console.log(`player: ${player}`);
即使帐户设置为文字,我仍然会得到undefined for profileId 以上。这很奇怪..?
最终解决方案 (在codepen.io 中运行它,因为你需要加载 lodash)
console.log(" Example Clean Code without Lodash")
console.log('===============================')
let account = {};
const game = { player: 'Sam' }
console.log(`account: ${account}`);
const { profileId = null } = account;
const { player } = game || {};
console.log(`profileId: ${profileId}`);
console.log(`player: ${player}`);
/* using IIFE so profileId doesn't conflict with example above */
(() => {
console.log("Example using unnecessary Lodash")
console.log('===============================')
let profileId = _.get(account, 'profileId', null);
const game = { player: 'Sam' }
console.log(`account2: ${account}`);
const { player } = game || {};
console.log(`profileId: ${profileId}`);
console.log(`player: ${player}`);
})();
【问题讨论】:
-
“更好”是一个广义的术语。
标签: javascript reactjs lodash