Javascript Javascript比较一个数组中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11092280/
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
Javascript compare items in one array
提问by nvrmore100
Pardon my complete lack of javascript knowledge in advance, but I can't seem to find a good example of how to compare two arrays and create another array based the results.
请原谅我完全缺乏 javascript 知识,但我似乎找不到一个很好的例子来说明如何比较两个数组并根据结果创建另一个数组。
I am attempting to get a list of user accounts from a storage device (uses javascript and handles MOST functions ok), and compare them against a statically created list of "good" users.
我正在尝试从存储设备获取用户帐户列表(使用 javascript 并正常处理 MOST 功能),并将它们与静态创建的“好”用户列表进行比较。
Using a switch statement works but I really do not like it, and I'm sure there is a much better way (userList is populated dynamically from the device when I query it):
使用 switch 语句可以工作,但我真的不喜欢它,而且我确信有更好的方法(当我查询时,从设备动态填充 userList):
for (userName = 0; userName < userList.length; userName++) {
switch (userList[userName]) {
case 'someuser1':
printf('Username: ' + userList[userName] + ' is good\n');
break;
case 'someuser2':
printf('Username: ' + userList[userName] + ' is good\n');
break;
case 'someuser3':
printf('Username: ' + userList[userName] + ' is good\n');
break;
default:
printf('Username: ' + userList[userName] + ' is NOT good\n');
}
}
I would like to create a third array of "bad users" and compare them against a new array of "good users", and "found users". I have started with:
我想创建第三个“坏用户”数组,并将它们与新的“好用户”和“找到的用户”数组进行比较。我已经开始:
var goodUsers = ["someuser1", "someuser2", "someuser3"];
However I can't figure out the right combination of multiple for loops, if statements, or otherwise to compare the two and give me an array of the "bad users" that I can loop through and perform actions against.
但是,我无法找出多个 for 循环、if 语句或其他方式的正确组合来比较两者并给我一个“坏用户”数组,我可以循环遍历并对其执行操作。
Any help would be appreciated!
任何帮助,将不胜感激!
回答by Jason Kulatunga
Use indexOf
to find if the user exists in your array.
使用indexOf
发现,如果用户阵列中存在。
var goodUsers = ["someuser1", "someuser2", "someuser3"];
var storedUsers = ["someuser1", "user", "user3"];
for(var goodUser in goodUsers){
if(storedUsers.indexOf(goodUsers[goodUser])>-1){
console.log('User:' + goodUsers[goodUser] + ' is good.')
}
}
?
回答by Alex Wayne
Array's indexOf
method is sweet. It returns the position of an element in the array, if it exists, or returns -1 if it does not.
Array 的indexOf
方法很好用。如果存在,则返回数组中元素的位置,如果不存在,则返回 -1。
var goodUsers = ["someuser1", "someuser2", "someuser3"];
var users = ["someuser1", 'basuser'];
var user;
for (var i=0; i < users.length; i++) {
user = users[i];
if (goodUsers.indexOf(user) >= 0) {
console.log(user + ' is a good user');
} else {
console.log(user + ' is BAD!!!');
}
}?
回答by jfriend00
For larger lists, a more efficient way than .indexOf
is to put your good user list into an object and use direct lookup on that object. This also works in older browsers as it doesn't require the Array.indexOf()
method.
对于较大的列表,比.indexOf
将好的用户列表放入对象并在该对象上使用直接查找更有效的方法。这也适用于较旧的浏览器,因为它不需要该Array.indexOf()
方法。
var goodUsers = {
"someuser1": true,
"someuser2": true,
"someuser3": true
};
Then, you can check to see if a user is in that list with:
然后,您可以使用以下命令检查用户是否在该列表中:
if (goodUsers[user])
For longer lists, this is a lot more efficient than using indexOf which just iterates through the array comparing each item in the array to your target because this uses a hash lookup (like a hash table).
对于较长的列表,这比使用 indexOf 效率高得多,indexOf 只是遍历数组,将数组中的每个项目与您的目标进行比较,因为它使用哈希查找(如哈希表)。
If you had a candidate set of users and you wanted to know which ones were in the goodUsers
list, you could do that like this:
如果您有一组候选用户,并且想知道goodUsers
列表中的哪些用户,您可以这样做:
var goodUsers = {
"someuser1": true,?
"someuser2": true,?
"someuser3": true
};
var candidateUsers = ["someuser4", "someuser1", "someuser5", "someuser2", "someuser6", "someuser3", "someuser7"];
function checkUsers(candidates) {
var goods = [];
for (var i = 0, len = candidates.length; i < len; i++) {
var item = candidates[i];
if (goodUsers[item]) {
goods.push(item);
}
}
return(goods);
}
var validUsers = checkUsers(candidateUsers);
Edit:
编辑:
While this object lookup still works in modern Javascript, there is now a Set
and Map
object in ES6 that can do this cleaner and more efficiently. For the user lookup, you would probably use the Set
object.
虽然这种对象查找在现代 Javascript 中仍然有效,但现在ES6 中有一个Set
andMap
对象可以更清晰、更有效地完成这项工作。对于用户查找,您可能会使用该Set
对象。
const goodUsers = new Set(["someUser1", "someUser2", "someUser3"]);
goodUsers.add("someUser4");
if (goodUsers.has(user)) {
// user is in the set
}
回答by Caleb
The brute force method would be something like this:
蛮力方法是这样的:
var users = []; // here is where you get the users from the device
var goodUsers = []; // here you get your good users list
var badUsers = []; // initialize an empty array for bad users
for (var i=0; i< users.length; i++) {
var isAGoodUser = false;
for(var y=0; y< goodUsers.length; y++) {
if(users[i] == goodUsers[y]) {
printf('Username: ' + users[i] + ' is good\n');
isAGoodUser = true;
break;
}
}
if(!isAGoodUser){
printf('Username: ' + users[i] + ' is NOT good\n');
badUsers.push(users[i]);
}
}
回答by pete
I like the indexOf
method for this. Example fiddle: http://jsfiddle.net/8MV3J/
我喜欢这个indexOf
方法。小提琴示例:http: //jsfiddle.net/8MV3J/
var good = ["someuser1", "someuser2", "someuser3"];
var bad = [];
var ugly = ["someuser4", "someuser1", "someuser5", "someuser2", "someuser6", "someuser3", "someuser7"];
var i = 0;
var li;
for (i = 0; i < ugly.length; i += 1) {
if (good.indexOf(ugly[i]) === -1) {
bad.push(ugly[i]);
}
}
for (i = 0; i < bad.length; i += 1) {
li = $('<li />').text(bad[i]);
$('ul#bad').append(li);
}?