首页 > 解决方案 > ES6 迭代包含 const

问题描述

有人可以解释为什么我在这段代码中出现错误吗?顺便说一句,我在 es6 中还是新的,谢谢

selData.map((item,idx)=>({ 

        const TargetItem = aclEntries.findIndex(rec=>rec.stakeholder_id===item.value)          

        console.log(TargetItem)  



        }))    

标签: javascript

解决方案


ES6 函数可以用几种不同的方式编写。

// If you have more than 1 param, you have to wrap them with `()`
const functionName = (param1, param2) => { return console.log(param1, param2); }

// If you're just returning a value, you can omit the `{}`
const functionName = (param1, param2) => console.log(param1, param2);

// If you only have 1 param, you can omit the `()` around the params
const functionName = param1 => console.log(param);

我在下面的代码中添加了另一个示例.find(),它将为您提供 的结果aclEntries,而不仅仅是索引位置。

另外,我使用forEach而不是map, asmap创建了一个新数组,并且您没有将返回值分配给map变量以供以后使用。

const aclEntries = [
  { stakeholder_id: '1234', taco: 'cat' }
];
const selData = [
  { value: '1234' }
];

selData.forEach((item) => {
  const TargetItemIndex = aclEntries.findIndex(rec => rec.stakeholder_id === item.value);
  const TargetItemContent = aclEntries.find(rec => rec.stakeholder_id === item.value);
  
  console.log('index', TargetItemIndex);
  console.log('content', TargetItemContent);
})


推荐阅读