0

datastatusMonthly[0] - This is my String in javascript If i print this, it is printing as same string.

How do i get the value of '0' index in array datastatusMonthly using this above string?

Any help please?

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
  • Don't use a string? Please include some indication of how you're using this code, where it comes from, etc. Context will help determine the best option to use. – Heretic Monkey Jun 30 '17 at 13:32
  • Do you want the answer to work for only that specific string? A string in the form datastatusMonthly[#] where # could be any number? could the array have multiple entries? ie datastatusMonthly[#, #, #]. Please be a little more specific about the possible range of inputs. – Marjorie Pickard Jun 30 '17 at 13:35

3 Answers3

2

You can use eval. The eval function will evaluate your string. JS bin here https://jsbin.com/guqoqukoqa/edit?js,console

Titouan56
  • 6,932
  • 11
  • 37
  • 61
0

Solution without eval, which is evil, using regex with group:

var datastatusMonthly = [3];

var text = 'datastatusMonthly[0]';
var regex = /(datastatusMonthly)\[([0-9]+)\]/g;
var match = regex.exec(text);

var arrayName = match[1];
var arrayIndex = match[2];

console.log(window[arrayName][arrayIndex]);
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
0

This dose't have to be in a String i guess. correct me if i am not understanding it properly var fistElement = datastatusMonthly[0]; This link might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Accessing_array_elements

amittn
  • 2,249
  • 1
  • 12
  • 19