Why does javascript#39;s quot;inquot; operator return true when testing if 0 exists in an array that doesn#39;t contain 0?(为什么javascript的“in?运算符在测试不包含 0 的数组中是否存在 0 时返回 true?)
问题描述
为什么 Javascript 中的in"运算符在测试数组中是否存在0"时返回 true,即使数组似乎不包含0"?
Why does the "in" operator in Javascript return true when testing if "0" exists in array, even when the array doesn't appear to contain "0"?
例如,这返回 true,并且有意义:
For example, this returns true, and makes sense:
var x = [1,2];
1 in x; // true
这返回 false,并且有意义:
This returns false, and makes sense:
var x = [1,2];
3 in x; // false
但是这返回 true,我不明白为什么:
However this returns true, and I don't understand why:
var x = [1,2];
0 in x;
推荐答案
指的是索引或键,而不是值.0 和 1 是该数组的有效索引.还有有效的键,包括 length" 和 toString".试试 2 in x.这将是错误的(因为 JavaScript 数组是 0 索引的).
It refers to the index or key, not the value. 0 and 1 are the valid indices for that array. There are also valid keys, including "length" and "toString". Try 2 in x. That will be false (since JavaScript arrays are 0-indexed).
请参阅 MDN 文档.
这篇关于为什么javascript的“in"?运算符在测试不包含 0 的数组中是否存在 0 时返回 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么javascript的“in"?运算符在测试不包含 0 的数组中是否存在 0 时返回 true?
基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
