为什么不显示“ myValue = myArray [1.5];”返回错误?

时间:2019-03-16 14:45:17

标签: javascript arrays compiler-errors

为了从数组中获取项目,获取项目的值必须是整数。像这样:

var myArray = ["apples", "oranges", "sugar", "onions", "steak"];
alert(myArray[2]);//2 is the integer I'm talking about

但是,以下代码仍然可以正常工作。

var myArray = ["apples", "oranges", "sugar", "onions", "steak"];
alert(myArray[1.5]);//1.5 is the decimal(float) value I'm talking about

为什么系统不自动舍入该值?还是至少在小数点后给出错误?以下代码不返回任何错误:

try {
var myArray = ["apples", "oranges", "sugar", "onions", "steak"];
var healthy = myArray[1.5];
} catch (e) {alert(e);}

系统为什么不将值四舍五入到最接近的整数或返回错误?

1 个答案:

答案 0 :(得分:1)

JavaScript中的数组是对象(即typeof [] === 'object')。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Description

  

数组是类列表对象,其原型具有执行遍历和变异操作的方法。 [...]

     

数组不能使用字符串作为元素索引(如在关联数组中一样),但必须使用整数。使用括号符号(或点符号)通过非整数设置或访问将不会设置或检索数组列表本身中的元素,而是会设置或访问与该数组的对象属性集合关联的变量。数组的对象属性和数组元素列表是分开的,并且数组的遍历和变异操作无法应用于这些命名属性。

由于数组是对象,因此可以向其添加新属性:

var myArray = ["apples", "oranges", "sugar", "onions", "steak"];
myArray.foo = 'bar';
myArray[1.5] = 'baz';

对象属性始终是字符串。现在,当您尝试访问myArray[1.5]时,您不是在访问数组索引,而是访问值为myArray['1.5']的属性baz

相关问题