gpt4 book ai didi

javascript - 为什么 "myValue = myArray[1.5];"不返回错误?

转载 作者:行者123 更新时间:2023-11-30 19:43:09 25 4
gpt4 key购买 nike

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

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);}

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

最佳答案

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

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

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. [...]

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

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

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

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

关于javascript - 为什么 "myValue = myArray[1.5];"不返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55198002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com