javascript - 如何在 Javascript 数组中查找单词(字符串)?
问题描述
我需要检查我的数组是否有这个词
这是我的代码请帮忙
var name = ['heine', 'hans'];
var password = ['12343', '1234'];
function login() {
var pos;
if(name.includes('hans')) {
console.log("enthält");
pos = name.indexOf('hans');
console.log(pos)
if(password[pos] === '1234') {
console.log("angemeldet")
}
}
}
consoleout = 6,但是为什么,它必须是 1
如果单词hans
在数组中,那么我需要数组中单词的位置
解决方案
你可能会发现some()
这很方便。它将索引传递给回调,您可以使用它从passwords
数组中找到相应的值:
function test(name, pw) {
let names = ["heine", "hans"];
let passwords = ["12343", "1234"];
// is there `some` name/pw combinations that matches?
return names.some((n, index) => name == n && pw == passwords[index])
}
console.log(test("hans", '1234')) // true
console.log(test("hans", '12345')) // false
console.log(test("hans", '12343')) // false
console.log(test("heine", '12343')) // true
console.log(test("mark", '12343')) // false
推荐阅读
- machine-learning - 我将如何计算非线性(rbf 内核)svm 中距超平面/决策边界的边距距离?
- flutter - 如何在没有 Cupertino 底栏的情况下路由到新页面
- c# - 带有 TextWrap 的单元格行不会使用 EPPlus 自动调整大小
- architecture - 构建身份验证服务所需的架构
- tensorflow - 名称 tf.Session 已弃用。请改用 tf.compat.v1.Session
- javascript - 仅在数字相等时才发现如何修复 HCF
- scala - 在控制器的方法中不使用列表中的头部
- bootstrap-4 - 我有一个关于将元素向右推的问题
- docker - `docker-compose run client yarn lint`与`cd client && yarn lint`有什么区别
- python - 如果另一列中存在任何值 >0,则需要为数据框分配值