[英]Array.every returns false instead of true
I'm working on something and I wrote this code that seems to return false instead of true: 我正在做一些事情,我写了这段代码,似乎返回false而不是true:
function checkValidUsers(validUsers)
{
var validIds = validUsers.map(function (user) { return user.id; });
return function (users)
{
var ids = users.map(function (user) { return user.id; });
return ids.every(function (id) { return id in validIds; } );
}
}
var check = checkValidUsers([{ id: 1 }, { id: 2 }, { id: 3 }]);
check([{ id: 2 }, { id: 3 }]); // return false
The two map functions return the correct arrays ([1,2,3] for the first and [2,3] for the second), But every function does not for some reason. 这两个映射函数返回正确的数组(第一个返回[1,2,3],第二个返回[2,3]),但是每个函数都不出于某种原因。
Can anyone help me find the bug in the code? 谁能帮我找到代码中的错误?
Don't use in
to check whether an element in an array. 不要使用
in
检查数组中的元素。
Instead , use .indexOf
method. 而是使用
.indexOf
方法。
return ids.every(function (id) { return validIds.indexOf(id) != -1; });
in
can be used like this with coffeescript, but in JS, it's just a iterator operator. in
可以与coffeescript一起使用,但是在JS中,它只是一个迭代器运算符。 Try with: 尝试:
return ids.every(function (id) { return ~validIds.indexOf(id); });
There are some missing/wrong characters in your code, here is a complete working code: 您的代码中有一些丢失/错误的字符,这是一个完整的工作代码:
function checkValidUsers(validUsers) {
var validIds = validUsers.map(function (user) { return user.id; });
return function (users) {
var ids = users.map(function (user) { return user.id; });
return ids.every(function (id) { return ~validIds.indexOf(id); });
};
}
var check = checkValidUsers([
{ id: 1 }, { id: 2 }, { id: 3 }
]);
check([{ id: 2 }, { id: 3 }]);
If you want use in you need a bit change you validIds 如果要在其中使用,则需要进行一些更改,您的validIds
var validIds = validUsers.reduce(function (acc,user) {
acc[user.id]=true;
return acc;
},{});
function checkValidUsers(validUsers) { var validIds = validUsers.reduce(function (acc,user) { acc[user.id]=true; return acc; },{}); return function (users) { var ids = users.map(function (user) { return user.id; }); return ids.every(function (id) { return id in validIds; }); } } var check = checkValidUsers([ { id: 1 }, { id: 2 }, { id: 3 }]); document.getElementById('res').innerHTML = check([{ id: 2 }, { id: 3 }]);
<div id="res"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.