I have 3 defined variables.
var age = 25;
var name = 'vincent';
var work = 'painter';
below function required to assign corresponding values to the variables.
function assign(_data){
//_data contains "age_25" and it might be "Name_Raja"
//this can be any one of the three variables.
}
How to identify the corresponding variable from the data?
Ashwin Prabhu
7,6545 gold badges54 silver badges83 bronze badges
-
is _data a list? why not a dictionary?Ronen Ness– Ronen Ness2015年07月15日 09:25:42 +00:00Commented Jul 15, 2015 at 9:25
2 Answers 2
Use indexOf of to identify what data contains
var name = '',
age = 0,
work = '';
function assign(_data) {
_data = _data.toLowerCase();
if (_data.indexOf('name_')) {
name = _data.split('_')[1];
}
else if (_data.indexOf('age_')) {
age = parseInt(_data.split('_')[1]);
}
else if (_data.indexOf('work_')) {
work = _data.split('_')[1];
}
}
timothyclifford
6,9997 gold badges61 silver badges86 bronze badges
answered Jul 15, 2015 at 9:31
Amit.rk3
2,4172 gold badges12 silver badges16 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
function assign(_data){
window[_data.split("_")[0]] = _data.split("_")[1];
}
This assigns the value of the corresponding key.
Comments
lang-js