问题
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);
回答1:
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"]));
来源:https://stackoverflow.com/questions/27895644/tostring-for-each-element-of-an-array-in-javascript