如何从javascript中的数组中获取值?

时间:2014-04-09 13:22:53

标签: javascript cookies

让阵列成为     var array =     [     “我=萨尔曼”,“专业=学生”,“班级=高中”     ]

如何在这里提取'我'的值?

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

您需要在数组中搜索所需的字符串部分,然后从指定的字符串中删除您搜索的内容。

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
    }
}

答案 2 :(得分:0)

试试这个:

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

或功能:

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') );