使用其索引值显示数组项

时间:2017-11-26 08:15:46

标签: javascript angular

我有函数showEmployee(i),它返回一个数组对象的索引。

使用索引值我需要显示返回索引的值。

我无法弄明白该怎么做。我累了congole.log(i),返回undefined

以下是我的代码。请帮忙

Employees =[
    {'name':'Arun','role':'Developer'},
    ....
  ];

showEmployee(i){
   console.log(i); // this returns the index value of the array
}

1 个答案:

答案 0 :(得分:0)

以下是在Javascript中执行此操作的方法,我们可以通过执行<<arrayName>>[<<index of the array element>>]访问数组元素,请参阅以下代码段并告诉我这是否可以解决您的问题!

如果要在数组中返回特定值,可以在return Employees[i].name函数中执行return Employees[i].roleshowEmployee()

注意:

  1. 需要使用Employees语法定义(var << variable name >> = <<something>>)等变量。

  2. 函数应定义为

    function <<function name>>(<< function parameters){
    
     }
    
  3. var Employees = [
        {'name':'Arun','role':'Developer'},
        {'name':'Arun2','role':'Developer2'},
        {'name':'Arun3','role':'Developer3'},
        {'name':'Arun4','role':'Developer4'},
        {'name':'Arun5','role':'Developer5'}
      ];
    
    function showEmployee(i){
       console.log(Employees[i]); // this returns the index value of the array
    }
    
    showEmployee(2);
    showEmployee(3);
    showEmployee(4);
    .as-console {
        height: 100%;
    }
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }