1

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
asked Jul 15, 2015 at 9:21
1
  • is _data a list? why not a dictionary? Commented Jul 15, 2015 at 9:25

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1
function assign(_data){
 window[_data.split("_")[0]] = _data.split("_")[1];
}

This assigns the value of the corresponding key.

answered Jul 15, 2015 at 9:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.