[英]Check value in angular array
Hello guys i cant find actually info about convert string to array and after check them.Im trying check have this post in usermeta or not. 大家好,我找不到有关将字符串转换为数组的实际信息,并检查了它们。我正在尝试检查是否在usermeta中发布了这篇文章。 Before converting to array this string.
在转换为数组之前,此字符串。 But it doesnt work why?
但这为什么不起作用?
$scope.like = function(id) {
PostService.GetUserMeta(user).then(function(data) {
var likes = '290 270'
var check_likes = likes.split(" ");
if (check_likes != id) {
$http.jsonp('http://somesite.com/api/userplus/update_user_meta_vars/', {
params: {
like_post: id + ',' + likes,
callback: "JSON_CALLBACK"
}
}).success(function(data) {
console.log('Id added to array');
});
} else {
console.log('ID already in array');
}
})
}
The problem lies in statement 问题在于声明
if(check_likes != id)
Here check_likes
is an array thus it will never be equal to id
这里
check_likes
是一个数组,因此它永远不会等于id
I think you need to create a number array. 我认为您需要创建一个数字数组。
var check_likes = likes.split(" ").map(Number);
Then you can use .indexOf() to check whether id
exists in an array, it returns the first index at which a given element can be found in the array, or -1
if it is not present. 然后,您可以使用.indexOf()来检查
id
是否存在于数组中,它返回可以在数组中找到给定元素的第一个索引;如果不存在,则返回-1
。
if (check_likes.indexOf(id) == -1){
$http.jsonp(.....)
}else{
console.log('ID already in array');
}
You can't compare an object of type Array
to a primitive data type like your id
parameter. 您无法将
Array
类型的对象与原始数据类型(如id
参数)进行比较。
Try wrapping your code inside a loop like so: 尝试将代码包装在一个循环中,如下所示:
for(i = 0; i < check_likes.length; i++){
if (check_likes[i] != id) {
$http.jsonp('http://somesite.com/api/userplus/update_user_meta_vars/', {
params: {
like_post: id + ',' + likes,
callback: "JSON_CALLBACK"
}
}).success(function(data) {
console.log('Id added to array');
});
} else {
console.log('ID already in array');
}
}
Try this code: 试试这个代码:
$scope.like = function(id) {
PostService.GetUserMeta(user).then(function(data) {
var likes = '290 270'
var check_likes = likes.split(" ");
if (check_likes.indexOf(id) == -1) {
$http.jsonp('http://somesite.com/api/userplus/update_user_meta_vars/', {
params: {
like_post: id + ',' + likes,
callback: "JSON_CALLBACK"
}
}).success(function(data) {
console.log('Id added to array');
});
} else {
console.log('ID already in array');
}
})
}
After splitting likes
string you have an array of 2 strings, and you should check that your id param is not in that array to execute your request. 分割点
likes
字符串后,您将拥有2个字符串的数组,并且应检查id参数是否不在该数组中以执行请求。 The !=
would not work !=
不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.