[英]Get array count in Javascript
我有一个像这样的数组:
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 = [
'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中引起一些问题。 只是要清楚:)
由于将它们设置为对象,因此可以按以下方式访问它们:
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.