2 回答
TA贡献1815条经验 获得超6个赞
习惯最常见的数组原型方法(如.some())将有助于解决这类问题。
export const users = [
{ id: 0, name: 'user1', password: 'asd1' },
{ id: 0, name: 'user2', password: 'asd2' },
{ id: 0, name: 'user3', password: 'asd3' },
];
那么你postDetails需要看起来像这样:
import { users } from '...';
// ...
postDetails() {
const isUserValid = users.some(user => {
const username = this.state.userName;
const password = this.state.password;
return user.name === username && user.password === password;
});
this.setState({ message: isUserValid });
};
TA贡献1824条经验 获得超5个赞
有一个功能,它首先尝试找到一个用户,然后如果我们找到具有相同名称的对象,我们检查密码。如果某些内容无效,则该函数返回 false,否则返回 true
const users =[
{id:1,name:"mahesh",password:"mahesh123"},
{id:2,name:"abc",password:"abc123"}
]
const validation = (login, password) => {
const user = users.find(user => login === user.name) // find the user with same name
if (typeof user !== 'undefined') { // check the user. If we didn't find a object with same name, user will be undefined
return user.password === password // if passwords match it returns true
}
return false
}
console.log(validation('mahesh', 'mahesh123'))
console.log(validation('abc', 'abc123'))
console.log(validation('abc', 'sffh'))
console.log(validation('abdsawec', 'abc123'))
添加回答
举报