如何在angular或javascript中从数组中获取匹配字符串元素
我有3个div并单击事件,我在每个事件中使用一个变量并调用一个函数。 现在我有一个数组如何在angular或javascript中从数组中获取匹配字符串元素,javascript,angular,Javascript,Angular,我有3个div并单击事件,我在每个事件中使用一个变量并调用一个函数。 现在我有一个数组this.newarray=[“一”、“二”、“三”]我想用变量匹配数组中的元素。如果成功,则需要显示警报。我已经静态地进行了注释,但我需要从数组元素中进行注释。下面是代码 app.component.html 我试试看 function1() { for (let i = 0; i < this.newArray.length; i++) if (this.newArray[i]
this.newarray=[“一”、“二”、“三”]代码>我想用变量匹配数组中的元素。如果成功,则需要显示警报
。我已经静态地进行了注释,但我需要从数组元素中进行注释。下面是代码
app.component.html
我试试看
function1() {
for (let i = 0; i < this.newArray.length; i++)
if (this.newArray[i] === this.matchOutput){
alert("hello");
break;
}
}
在您的示例中,您将索引与字符串值进行比较
您还可以使用hashmap或set
const hash = new Set(['one', 'two', 'three'])
function1() {
if (this.hash.has(this.matchOutput))
alert('hello');
}
您正在将字符串值与函数1()中的索引(数字)进行比较
如果您想检查新数组是否包含匹配输出,那么您可以简单地使用includes方法。
尝试:
if(this.newarray.includes(this.matchoutput)){
警惕(“你好”);
}
这是否回答了您的问题?刚刚回答了你的问题它能解决你的问题吗?
function1() {
for (let i = 0; i < this.newArray.length; i++)
if (this.newArray[i] === this.matchOutput){
alert("hello");
break;
}
}
if(this.newArray.includes(this.matchOutput))
alert('hello')
const hash = new Set(['one', 'two', 'three'])
function1() {
if (this.hash.has(this.matchOutput))
alert('hello');
}