最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - IndexOf in a function - Stack Overflow

programmeradmin3浏览0评论

How can I return the index position of "needle" in this array?

function findNeedle(haystack) {
  return findNeedle.indexOf('needle');
}

findNeedle(['3', '123124234', undefined, 'needle', 'world', 'hay', 2, '3', true, false]);

How can I return the index position of "needle" in this array?

function findNeedle(haystack) {
  return findNeedle.indexOf('needle');
}

findNeedle(['3', '123124234', undefined, 'needle', 'world', 'hay', 2, '3', true, false]);

Share Improve this question edited Jun 22, 2016 at 7:28 Quentin Roy 7,8972 gold badges34 silver badges52 bronze badges asked Jun 22, 2016 at 7:20 Dimitris XydasDimitris Xydas 2332 gold badges5 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

make it

return haystack.indexOf('needle');

you need to use the argument you have passed to the function instead of the function itself.

findNeedle is the function, not the array that is passed as an argument of the function. Inside the function, haystack is your array.

function findNeedle(haystack) {
  return haystack.indexOf('needle');
}

var result = findNeedle(['3', '123124234', undefined, 'needle', 'world', 'hay', 2, '3', true, false]);

console.log(result);

You shoudn't run method .indexOf() on function. Call it on your property haystack instead.

return haystack.indexOf('needle');
发布评论

评论列表(0)

  1. 暂无评论