简体   繁体   中英

I am unable to implement the forEach loop in JavaScript

This is the image of the array named database I am using

I don't know how to use the forEach loop properly, can someone say why this does not work? This is what I tried.

The reason your forEach loop doesn't work is that you are passing it a function that looks like this:

function f(user, password) {
  password == 'examplepassword';
  user == 'someuser';
}

Your function is taking the wrong parameters. forEach goes over an array, and passes each item of the array to the function you are giving it. The function should be instead written like:

function f(item) {
  item.password == 'examplepassword';
  item.user == 'someuser';
}

So you would want to rewrite your code to be more like

db = [{username: 'a', password: 'abc'}, {username: 'b', password: 'bca'}]

db.forEach(function(user) {
  console.log("user " + user.username + " has password " + user.password);
})
/* Output:
user a has password abc
user b has password bca
*/

Extra credit:

You can find more details in the documentation for forEach . The function you pass forEach can also have two other arguments, the nº of the item it is currently passed, and the original array.

let a = ['a', 'b', 'c']
function f(item, position, array) {
  console.log("The letter " + item + " is in position " + position)
  console.log("array[position] == " + array[position])
}

a.forEach(f);

/* Output:
The letter a is in position 0
array[position] == a
The letter b is in position 1
array[position] == b
The letter c is in position 2
array[position] == c
*/

var database = [{
  username: 'gaurav',
  password: 'password'
}, {
  username: 'gaurav1',
  password: 'password1'
}, {
  username: 'gaurav2',
  password: 'password2'
}];

database.forEach(credential => {// credential is the object = {username, password}
  if (credential.username === credential.username && credential.password === credential.password) {
    console.log('matched');
  }
})

forEach will expect function having array of objects as "database" is having collection of objects. So we cannot have 2 separate parameters as you are passing "function (username, password)". It should be function(obj).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM