关于使用map,for等遍历数组获取其中每一项的值在调用接口只取到最后一个值的问题

接上一篇文章;
这里循环一个数组list,拿到其中的某些值,去做参数执行下一步的方法,需要这个参数(params)是变化的,但是在sendRightsParams方法中,输出的值总是数组的最后一项里面的内容,

      getRights(list) {
            const paramsKey = this.mediaForRights[this.type].keys.value;
            if (list && list.length) {
                list.map((item, index) => {
                    const params = item.name;
                    const temp = item[this.mediaForRights[this.type].keys.id];
                    this.$set(params, paramsKey, temp);
                    this.sendRightsParams(params, index);
                });
            }
        },

造成的原因:
这里给paramsKey赋值的话,每次重新的遍历会覆盖掉之前的值;
修改之后的代码

    getRights(list) {
            const paramsKey = this.mediaForRights[this.type].keys.value;
            if (list && list.length) {
                list.map((item, index) => {
                    const params = Object.assign({}, item.name);
                    const temp = item[this.mediaForRights[this.type].keys.id];
                    this.$set(params, paramsKey, temp);
                    this.sendRightsParams(params, index);
                });
            }
        },

另外:如果采用var来定义变量的话可能会经常遇到变量的作用域、变量提升问题;一般使用let比较好。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Spring 的 ApplicationContext 对象来获取所有的 Service,并将它们放到一个 Map 中,然后通过 key 调用对应的 Service。 下面是一个简单的示例代码: ```java @Service public class ServiceManager { @Autowired private ApplicationContext context; private Map<String, Object> serviceMap = new HashMap<>(); @PostConstruct public void init() { Map<String, Object> serviceBeans = context.getBeansWithAnnotation(Service.class); for (Object service : serviceBeans.values()) { Class<?>[] interfaces = service.getClass().getInterfaces(); if (interfaces.length > 0) { Class<?> serviceInterface = interfaces[0]; String serviceName = serviceInterface.getSimpleName(); serviceMap.put(serviceName, service); } } } public Object getService(String serviceName) { return serviceMap.get(serviceName); } } ``` 在上面的代码中,我们创建了一个 ServiceManager 类,使用 @Autowired 注解注入了 ApplicationContext 对象,然后在类的初始化方法 init 中,使用 ApplicationContext 对象获取所有被注解为 @Service 的 Service,并将它们放到一个 Map 中,key 为对应 Service 实现类的接口名。 最后,我们提供了一个公共方法 getService,用于根据 key 获取对应的 Service 对象。 使用该方法,我们可以方便地获取所有的 Service,并根据 key 调用对应的 Service。例如,我们可以在 Controller 中使用以下代码来获取 UserService 并进行相关操作: ```java @RestController public class UserController { @Autowired private ServiceManager serviceManager; @GetMapping("/user/{id}") public User getUser(@PathVariable Long id) { UserService userService = (UserService) serviceManager.getService("UserService"); return userService.getUserById(id); } } ``` 这样,我们就可以通过 ServiceManager 来管理所有的 Service,并在需要时根据 key 获取对应的 Service。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值