[英]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.