简体   繁体   中英

how to get values from an array in javascript?

let the array be var array= [ "me=Salman","Profession=student","class=highschool" ]

How do I extract the value of 'me' here?

Try this:

var result = '';
for(var values in array){
  if(values.indexOf('me=') !== -1 ){
    result = values.split('=')[1];
    break;
  }
}

You will need to search the array for your desired portion of the string, then remove what you searched for from the indicated string.

var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var findMatch = "me=";
var foundString = "Did not find a match for '"+findMatch+"'.";
var i = 0;

for (i = 0; i<array.length; i++) //search the array
{
    if(array[i].indexOf(findMatch) != -1) // if a match is found
    {
         foundString = array[i]; //set current index to foundString
         foundString = foundString.substring(findMatch.length, array[i].length); //remove 'me=' from found string
    }
}

Try this:

var a = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var result = a.filter(function(e){return /me=/.test(e);})[0]; // Find element in array
result = result.length ? result.split('=').pop() : null; // Get value

Or function:

var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];

function getVal(arr, key){
   var reg = new RegExp(key + '=');
   var result = arr.filter(function(e){ return reg.test(e)})[0];
   return result.length ? result.split('=').pop() : null;
}

console.log( getMe(array, 'me') );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM