在JavaScript中的运算符问题 [英] In operator issue in JavaScript

查看:70
本文介绍了在JavaScript中的运算符问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解JavaScript中的in运算符时遇到了一些小问题。
为什么我不能在下面的例子中找到 if 块?我该怎么做?

I've got small problem in understanding "in" operator in JavaScript. Why can't I go to the if block in example below? How do I do it?

var ar = [];
var a = 4;
ar.push(a);

if (a in ar){
    console.log("in if");
}

console.log(ar);
console.log(a);
console.log(typeof(ar[0]));
console.log(typeof(a));


推荐答案

in 运算符测试对象中是否存在给定的属性名称,它不会搜索值。如果 ar [a] 存在, a in 将为true。在您的示例中, ar [0] 存在,但 ar [4] 不存在,因此 a in 为false。

The in operator tests whether the given property name exists in an object, it doesn't search the values. a in ar will be true if ar[a] exists. In your example, ar[0] exists, but ar[4] doesn't, so a in ar is false.

要搜索数组中的值,请使用 indexOf 功能。它返回找到的元素的数组索引,如果找不到该值,则返回 -1

To search values in an array, use the indexOf function. It returns the array index of the found element, or -1 if the value can't be found.

if (ar.indexOf(a) != -1) {
    console.log("in if");
}

这篇关于在JavaScript中的运算符问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆