Javascript 如何使用AngularJS检查值是否在数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31775953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if value is in array with AngularJS
提问by teddybear123
is there an AngularJS way of checking if a value exists in an array
是否有一种 AngularJS 方法来检查数组中是否存在一个值
var array1 = ["a","b","c"]
i'm trying to do this..
我正在尝试这样做..
var array2 = ["c", "d", "e"]
angular.forEach(array2, function (a) {
if (a /*is NOT in array1*/) {
array1.push(a);
} else {
return false
}
});
回答by juco
You can use Array.indexOf
which will return -1
if it's not found or the index of the value in the array.
如果未找到它或数组中值的索引,您可以使用Array.indexOf
which 将返回-1
。
So in your case:
所以在你的情况下:
if (array2.indexOf(a) < 0) {
array1.push(a);
}
回答by dfsq
You just need to use native Array.prototype.indexOfto check if value is in array or not:
您只需要使用本机Array.prototype.indexOf来检查值是否在数组中:
var array2 = ["c", "d", "e"]
angular.forEach(array2, function (a) {
if (array2.indexOf(a) === -1) {
// a is NOT in array1
array1.push(a);
}
});
回答by Dujardin Emmanuel
https://www.w3schools.com/jsref/jsref_includes_array.asp
https://www.w3schools.com/jsref/jsref_includes_array.asp
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");