-1

我刚刚想出了一个用于 javascript 的 inArray 实现,它运行良好。它很奇怪但很短,我感觉它有问题,但我不确定它是什么:

Array.prototype.inArray = function (itm) {
  return this.join("|").match( new RegExp('\\b'+itm+'\\b','ig')  );
}

更新:这应该是 inArray 功能的一般实现。我不确定哪个更昂贵,做一个循环或创建一个正则表达式

4

2 回答 2

0

I don't know what your implementation requirements are, but keep these in mind:

  • you'll be matching a stringified version of the Array members, not the actual members

  • the \\b will allow any word break, including punctuation, giving false positives.

  • it would only be useful for single word entries in the Array, otherwise you could get false positives

  • you'll be returning null or and Array of "matches". Not sure if that's what you'd want.

I'm sure these just scratch the surface.

If you are implementing a very narrow functionality, it could work, but would be not be adequate for general use.

于 2012-10-17T21:03:29.547 回答
0

使用 underscore.jsintersection()方法来确定您的数组是否包含一个元素甚至一系列元素:

if(_.intersection(yourArray, [item]).length){
    //do stuff
}

您也可以通过将它们推入数组来检查多个项目。它还涵盖任何类型的对象

于 2012-10-17T21:08:41.620 回答