浮点数组索引如何解释? [英] How are floating point array indices interpreted?
问题描述
我找不到关于此的任何信息,但假设我有
I can't find any information on this, but suppose I have
var arr = [1, 2, 3];
var x = arr[1.5];
我假设Javascript将floor
索引并返回索引1处的项目,但似乎至少在Chrome中,它仅返回undefined
.
I assumed that Javascript would floor
the index and returns the item at index 1, but it seems at least in Chrome it just returns undefined
.
这是正确的吗?我找不到任何可以证实这一点的标准或文档.如果这样的话,那真的很不方便,因为我认为舍入行为允许您将范围为[0,n)的任何浮点数传递给数组索引,但是如果执行浮点数学运算,看来您会默默地破坏数组.没有四舍五入.
Is this correct? I can't find any standard or documentation that confirms this. It's actually really inconvenient if so because I assumed the round-down behavior allows you to pass any float in the range [0, n) to an array index, but it seems you'll silently break your arrays if you do floating point math which isn't rounded.
如果有人维护javascript陷阱列表,请添加此列表.现在,我必须回顾1万行javascript代码,以查看我所做的这种假设在哪里悄悄地引起了错误!
推荐答案
根据 MDN:数组,数组项实际上是属性,而属性由字符串标识.
According to MDN: Array, array items are actually properties, and properties are identified by strings.
因此,访问arr[1.5]
与访问arr['1.5']
相同,而Firefox实际上就是这样做的.
Accessing arr[1.5]
is therefore the same as accessing arr['1.5']
, and Firefox does actually do it that way.
此代码:
var x = [0,1,2,3,4,5];
x[1.5] = 42;
alert(x);
alert(x['1.5']);
alert(x['1.50']);
输出:
0, 1, 2, 3, 4, 5
42
undefined
因此,使用浮点值访问的项是由数字的字符串表示形式标识的属性.请注意,使用'1.50'
访问项目与使用'1.5'
访问项目不同,因此索引不会转换为数字.
So, the item accessed using a floating point value is a property identified by the string representation of the number. Note that accessing an item using '1.50'
is not the same as accessing an item using '1.5'
, so the index is not converted to a number.
我也在Internet Explorer和Chrome中对此进行了测试,它们的作用都与Firefox相同.
I tested this in Internet Explorer and Chrome also, and they both do the same as Firefox.
这篇关于浮点数组索引如何解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!