需要更好的解决方案来简化JavaScript模式

时间:2017-08-04 06:40:07

标签: javascript design-patterns try-catch

对于似乎必须有更好的解决方案,我有相当详细的代码:

我需要根据对象ID找到数组的索引。我最初有这样的代码:

idx = (state.store.addresses || []).findIndex(x => x.location == location_name)
if (idx > -1) { /* do something */}

但后来我收到了以下错误:

Uncaught (in promise) TypeError: Cannot read property 'addresses' of undefined

我认为短路操作符会导致它跳转到使用空白数组[]时出现这样的错误,从而返回-1

由于该解决方案不起作用,我在try...catch语句中包含了8个这样的语句,而且这段代码变得冗长而冗长。

除了以下内容之外,还有更好的方法来处理此代码吗?

try {
    idx = state.store.addresses.findIndex(x => x.location == location_name)
    state.store.addresses[idx]['deleted'] = false
    set(state.store.addresses[idx], 'deleted', false)
} catch (e) {}

try {
    idx = state.store.customer.addresses.findIndex(x => x.location == location_name)
    state.store.customer.addresses[idx]['deleted'] = false;
    set(state.store.customer.addresses[idx], 'deleted', false)
} catch (e) {}

// 5 more of these

0 个答案:

没有答案
相关问题