的toString()JavaScript中的数组中的每个元素 [英] toString() for each element of an array in Javascript

查看:151
本文介绍了的toString()JavaScript中的数组中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个元素,这可能是一个字符串或数字是否是一个数组里面。该数组是测试和元素是。到目前为止好,我有这样的code:

 功能比较(值,测试){
  //我们需要所有字符串化的值将它们与一个字符串比较
  返回test.map(函数(值){
    返回value.toString();
    })的indexOf(值)> -1;
  }
警报(比较(2,[1,2,3]));
警报(比较(2,[1,2,3]));

它不工作 。然而,它看起来恶魔复杂,由于这一事实,即的indexOf() 使用它不适合我的需要严格的平等。 A 哈克的方式将做以下,这也可以工作:

 返回test.join(|)分裂(|)的indexOf(值)GT;。 -1;

但它是简单地看到,如果测试是 [A,B | C,D] 然后我们有一个问题,因为我们会可以比较 A b C &安培; D 而不是 A B | C D 。查找的安全特性的也不是一个选项,因此该解决方案是无效的。 是否有这样做的的indexOf()与任何更简单的方法的正常的平等的?

编辑:我第一次尝试这样做,它出人意料地返回false从严格的平等,这就是为什么我做到了复杂的方式:

  [1,2,3]的indexOf(2)。


解决方案

您可以做类似下面的?

 功能比较(值,测试){
  返回test.indexOf(数(值))> -1 ||
        test.indexOf(字符串(值))> -1;
}
警报(比较(2,[1,2,3]));
警报(比较(2,[1,2,3]));

的另一种方式是使用阵列。 prototype.some

 功能比较(值,测试){
  VAR NUM =数(值)
      海峡=字符串(值);  返回test.some(功能(VAL){
    返回VAL === NUM​​ || VAL ===海峡;
  });
}
警报(比较(2,[1,2,3]));
警报(比较(2,[1,2,3]));

I want to find whether an element, that might be a string OR a number, is inside an array. The array is test and the element is value. So far so good, I have this code:

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. However it looks devilish complex due to the fact that indexOf() uses strict equality which doesn't suit my needs. A hacky way would be doing the following, which also works:

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

However it's simple to see that, if test is ["a", "b|c", "d"] then we have a problem since we'd be comparing a, b, c & d instead of a, b|c, d. Finding a safe character is also not an option, so this solution is not valid. Is there any easier way of doing an indexOf() with normal equality?

Edit: my first attempt was doing this, which returned unexpectedly false from the strict equality and that's why I did it the complex way:

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

解决方案

You could do something like the following?

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"]));

Another way would be to use 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"]));

这篇关于的toString()JavaScript中的数组中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆