【问题标题】:Get array count in Javascript在Javascript中获取数组计数
【发布时间】:2013-11-06 22:48:39
【问题描述】:

我有一个这样的数组:

elements = {
    opinions: ['p31/php/endpoint.php?get=opinions'], // function to call and API endpoint, php/endpoint.php
    top3positive: ['p31/php/endpoint.php?get=top3positive'], // function to call andAPI endpoint, php/endpoint.php
    top3negative: ['p31/php/endpoint.php?get=top3negative'], // function to call andAPI endpoint, php/endpoint.php
};

如何指向第一个数组。如果我这样做alert(elements[0]);,它不会像我期望的那样返回意见。 我做错了什么?

我需要根据它的顺序 0,1,2 等指向数组索引。

谢谢

【问题讨论】:

  • {} 表示法用于对象,而不是数组。你通过elements.opinions访问opinions
  • @whatyouhide 如果我需要按数字访问索引怎么办?如何将其转换为数组?
  • 我在这里发布了一个解释对象/数组混淆的答案。
  • 这个 w3school 网页展示了很多在 javascript 中使用数组的示例:w3schools.com/js/js_obj_array.asp

标签: javascript


【解决方案1】:

{} 表示法创建对象,而不是数组。因此,它们不是整数索引的,并且必须使用经典的点表示法或使用 [] 来访问它们的属性。

如果你想要一个数组,这是构建它的正确方法:

elements = [
    'p31/php/endpoint.php?get=opinions', // function to call and API endpoint, php/endpoint.php
    'p31/php/endpoint.php?get=top3positive', // function to call andAPI endpoint, php/endpoint.php
    'p31/php/endpoint.php?get=top3negative', // function to call andAPI endpoint, php/endpoint.php
];

如果您在问题中保留您的对象,您可以访问例如它的第一个元素是这样的:

elements.opinions;

elements['opinions'];

微编辑

我在数组中留下了一个逗号,这在现代浏览器中很好,但在旧版 IE 中可能会导致一些问题。只是要清楚:)

【讨论】:

  • 数组在 JS 中没有键。我的意思是你可以添加它们,但那是在滥用数据结构。(已解决)
  • OOOPS 对不起对不起对不起,我忘了删除它们 :)
  • 发生了,只是想澄清一下:)
  • 他需要知道如何将对象转换为数组,而不是像数组那样访问对象
  • @Brenden 对象不是有序集合,所以他不能把它转成数组,访问elements[0]时一定要访问opinions
【解决方案2】:

由于您将它们设置为对象,因此您可以通过以下方式访问它们:

elements['opinions'];
elements['top3positive'];
elements['top3negative'];

如果要将它们设置为数组,则:

var elements=['p31/php/endpoint.php?get=opinions','p31/php/endpoint.php?get=top3positive','p31/php/endpoint.php?get=top3negative'];

那么当你想访问数组中的项目时,你可以这样做:

elements[0];

【讨论】:

  • 是的,我明白这一点,但正如我所说,我需要通过带有数字的索引来访问它们。如何将此对象转换为数组
猜你喜欢
  • 2012-06-14
  • 2023-03-31
  • 2018-08-10
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多