在.map()内的数组上使用indexOf

时间:2017-11-09 15:19:57

标签: javascript

我从一个数组开始,想要查看该数组中是否已存在该键。

keys = ['pitch1']

var y = [
  {header: 'pitch1', data: 'pitch1 data'}, 
  {header: 'pitch3', data: 'pitch3 data'}, 
  {header: 'pitch4', data: 'pitch4 data'},
  {header: 'pitch2', data: 'pitch2 data'},
  {header: 'pitch1', data: 'more pitch 1 data'},
]


y.map((item, index) => {
  if (keys.indexOf[item.header]) {
    console.log('found it')
  } else {
    console.log('not found')
  }
})

这是回归:

"not found"
"not found"
"not found"
"not found"
"not found"

我做错了什么?

3 个答案:

答案 0 :(得分:1)

您的indexOf函数正在返回0

0是Javascript中的假值。改变你的状况如下:

if (keys.indexOf(item.header) >= 0)

答案 1 :(得分:1)

keys.indexOf[item.header]应为keys.indexOf(item.header)并将{if条件}更改为if (keys.indexOf(item.header) != -1) indexOf,当它找不到对象时返回-1

它返回-1而不是false的原因是字符串开头的针位于0位置,相当于Javascript中的false 。因此,返回-1可确保您知道实际上没有匹配。

keys = ['pitch1']

var y = [
  {header: 'pitch1', data: 'pitch1 data'}, 
  {header: 'pitch3', data: 'pitch3 data'}, 
  {header: 'pitch4', data: 'pitch4 data'},
  {header: 'pitch2', data: 'pitch2 data'},
  {header: 'pitch1', data: 'more pitch 1 data'},
]


y.map((item, index) => {
  if (keys.indexOf(item.header) != -1) {
    console.log('found it')
  } else {
    console.log('not found')
  }
})

答案 2 :(得分:0)

我建议将some()用于此目的,例如:

keys = ['pitch1']

var y = [
  {header: 'pitch1', data: 'pitch1 data'}, 
  {header: 'pitch3', data: 'pitch3 data'}, 
  {header: 'pitch4', data: 'pitch4 data'},
  {header: 'pitch2', data: 'pitch2 data'},
  {header: 'pitch1', data: 'more pitch 1 data'},
]

var found = y.some(v => keys.includes(v.header));
if (found) {
    console.log('found it')
} else {
    console.log('not found')
}