javascript - toString() 用于 Javascript 中数组的每个元素

标签 javascript arrays indexof

<分区>

我想查找一个元素(可能是字符串或数字)是否在数组中。数组是test元素是value .到目前为止一切顺利,我有这段代码:

function compare(value, test) {
  // We need to stringify all the values to compare them with a string
  return test.map(function(value){
    return value.toString();
    }).indexOf(value) > -1;
  }
alert(compare("2", [1, 2, 3]));
alert(compare("2", ["1", "2", "3"]));

It does work 。然而,由于indexOf(),它看起来非常复杂。 uses strict equality这不符合我的需要。 hacky 方法是执行以下操作,这也有效:

return test.join("|").split("|").indexOf(value) > -1;

但是很容易看出,如果 test 是 ["a", "b|c", "d"]那么我们有一个问题,因为我们要比较 a , b , c & d而不是 a , b|c , d .寻找安全字符 也不是一种选择,因此该解决方案无效。 有没有更简单的方法来做 indexOf()正常平等

编辑:我的第一次尝试是这样做的,它从严格相等中意外返回 false,这就是为什么我用复杂的方式来做:

["1", "2", "3"].indexOf(2);

最佳答案

你可以做类似下面的事情吗?

function compare(value, test) {
  return test.indexOf(Number(value)) > -1 || 
        test.indexOf(String(value)) > -1;
}
alert(compare("2", [1, 2, 3]));
alert(compare("2", ["1", "2", "3"]));

另一种方法是使用 Array.prototype.some :

function compare(value, test) {
  var num = Number(value),
      str = String(value);

  return test.some(function(val) {
    return val === num || val === str;
  });
}
alert(compare("2", [1, 2, 3]));
alert(compare("2", ["1", "2", "3"]));

关于javascript - toString() 用于 Javascript 中数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27895644/

相关文章:

javascript - 从输入 onclick 获取上一个 td

javascript - 这是哪个模板lang `<?js`

java - 打印数组内的内容

javascript - 如何测试一个字符串是否是另一个字符串的最后一个 “part”?

javascript - 为什么 Array.indexOf() 对一个 redux Action 正确工作,但对另一个 Action 却不行? (相同的 reducer )

javascript - 弄清楚如何为诸如push、indexOf之类的函数设置动态变量的问题

javascript - 同时有两个事件选项卡!我该怎么做?

javascript - 为什么下拉菜单不出现在 Safari 中?

在 X64 gcc 内联 asm 中调用 scanf

arrays - 获取 Swift 集合或数组中对象的下一个或上一个项目