javascript 如何打印数组索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6276346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:08:13  来源:igfitidea点击:

How to print array index

phpjavascripthtml

提问by user762267

Hi Guys Actually I want to print the array index for some purpose.Can anybody tell me about this ?

嗨,伙计们,实际上我想出于某种目的打印数组索引。有人可以告诉我吗?

回答by Oliver A.

Get the first index of an elemnt:

获取元素的第一个索引:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;

For all elemnts

对于所有元素

foreach($array as $key => $value){
    echo "{$key} => {$value}\n";
}

will output

会输出

0 => blue
1 => red
2 => green
3 => red

All keys:

所有键:

echo implode(', ',array_keys($array));

will output

会输出

 0, 1, 2, 3

回答by Touchpad

not sure what you mean with this question but you could try

不确定你对这个问题的意思,但你可以试试

echo "<pre>";
print_r ($arr);
echo "</pre>";

that way you'll see your entire array including all the indexes

这样你就会看到你的整个数组,包括所有的索引

回答by Chris Laarman

if you mean the keys of the array:

如果你的意思是数组的键:

$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

//result
Array
(
    [0] => 0
    [1] => color
)

This will provide an array of the keys

这将提供一组键