Passing a variable through to an array mid string - javascript

I have an array like this:
var array = [
'Hey there, ' + name + '!',
'It\'s nice to see ' + name + ' join us.',
'Everybody welcome ' + name + '!',
'Thanks,' + name
]
I get an error stating that name is undefined, so if I put name = ''; before it, and loop through the array, it just says
Hey there, !
It's nice to see join us.
Everybody welcome !
Thanks,
Is there a way I can do something like:
name = 'Albz'
console.log(array[0]);
and have it echo out
Hey there, Albz!
The name variable is dynamic and changes on each iteration of forEach, so it can't be hardcoded, and I'd like to not have to redeclare the array every single time as it's quite lengthy.
Is there a way to do this?

var nameArr = ['Ayan', 'Arnab', 'Akash'];
function process(name) {
return [
'Hey there, ' + name + '!',
'It\'s nice to see ' + name + ' join us.',
'Everybody welcome ' + name + '!',
'Thanks,' + name
];
}
for (var i = 0, len = nameArr.length; i < len; i += 1) {
console.log(process(nameArr[i])[0]);
}

Related

How to freeze text from moving in console.log

So I have a simple console.log script that prints this
Now when I add a letter is moves
any way to freeze it please?
code
It would probably make more sense to make all of your cells contain a space character if they are "empty". Take a look here:
var Cell_1 = "a";
var Cell_2 = " ";
var Cell_3 = " ";
var Cell_4 = " ";
var Cell_5 = " ";
var Cell_6 = " ";
var Cell_7 = " ";
var Cell_8 = " ";
var Cell_9 = " ";
console.log(
Cell_1 + "|" + Cell_2 + "|" + Cell_3 + "\n" +
Cell_5 + "|" + Cell_6 + "|" + Cell_6 + "\n" +
Cell_7 + "|" + Cell_8 + "|" + Cell_9 + "\n" +
)
This way all of your variables are the same width - one character.
For future reference, here's some code that would probably look a bit nicer:
// This is called a 2d array: essentially an array containing other arrays.
// Its good for storing grids or tables of information.
var cells = [
['a', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
// This uses Array.reduce() to generate the string.
// Google it once you feel more confident :)
console.log(
cells.reduce(
(totalString, currentRow) => totalString + currentRow.join('|') + '\n',
''
)
)
The question isn't very clear but I am assuming that you want to keep a grid aligned, the grid having multiple cells that can contain a character or not.
The problem is that the empty cells are initialised to "" (empty string) which is of size 0, but when a character is set the size will be 1, so it will shift all the following cells of 1.
An easy solution is to use a " " (space) for the empty cell instead of a "". As a result the size of a cell will always be 1 and the whole grid won't be shifted.

DRY programming with JavaScript Mad Libs Challenge

I am new to programming.
I know that I could use functions and loops to keep from repeating this code, but I need help. Anyone?
var questions = 3;
var questionsCount = ' [' + questions + ' questions left]';
var adjective = prompt('Please type an adjective' + questionsCount);
questions -= 1;
questionsCount = ' [' + questions + ' questions left]';
var verb = prompt('Please type a verb' + questionsCount);
questions -= 1;
questionsCount = ' [' + questions + ' questions left]';
var noun = prompt('Please type a noun' + questionsCount);
alert('All done. Ready for the message?');
var sentence = "There once was a " + adjective;
sentence += ' programmer who wanted to use JavaScript to ' + verb;
sentence += ' the ' + noun + '.';
document.write(sentence);
I'd use a string template which contains, eg, {{noun}} to be replaced with a noun, which uses a regular expression to prompt the user for replacements to make:
const template = 'There once was a {{adjective}} programmer who wanted to use JavaScript to {{verb}} the {{noun}}.';
let questions = 3;
const result = template.replace(
/{{(.*?)}}/g,
(_, typeOfSpeechNeeded) => prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)
);
console.log(result);
The regular expression
{{(.*?)}}
matches {{, followed by some characters, followed by }}, where those characters are put into a capturing group - this allows the .replace to examine the capturing group to determine what typeOfSpeechNeeded to display in the prompt.
The /g in the regular expression makes it global, which replaces all matches, not just the first match.
The backtick string is just a more readable way of interpolating strings:
prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)
is equivalent to
prompt('Please type a ' + typeOfSpeechNeeded + ', ' + questions-- + ' question(s) left')

Adding quotation mark in array values

I have an array of strings in object form received from file, only I need to add quotation mark around parameter names of objects which are strings inside an array and around their values between square brackets to convert those strings to proper objects.
["{Durdham Hall Electric: [e4.kwh]}", "{University Hall Substation: [e1.kwh]}",
"{University Hall Substation: [e2.kwh]}"]
I have no idea how to loop through values and to add required symbol in required part.
Maybe change
options.push('<option value="' + '{' + data[devices][1] + ': ' + '[' + 'e' + i + '.kwh' + ']' + '}' + '" >' + meterName + '</option>')
to something like this, then you get a little nice parsable JSON
var data = [[0, 'Durdham Hall Electric:']],
devices = 0,
meterName = 'meterName',
i = 3,
options = [];
options.push('<option value="' + '{ \\"device\\": \\"' + data[devices][1] + '\\", \\"kwh\\": \\"' + 'e' + i + '\\"}' + '">' + meterName + '</option>');
alert(options);
You can use Regex and forEach to do this:
var data = ["{Durdham Hall Electric: [e4.kwh]}", "{University Hall Substation: [e1.kwh]}",
"{University Hall Substation: [e2.kwh]}"];
data.forEach(function(v,i){
data[i] = JSON.parse( v.replace(/{(.+):\s\[(.*)\]}/g, '{"$1":["$2"]}') );
});
console.log(data); // Open your console to see the results
If the strings are always starting with a { you can use substring and then combine the string back together.
String part1;
String part2;
String result;
String str = "{Durdham Hall Electric: [e4.kwh]}"
Then use index of to find the :
part1 = str.subString(1, str.indexOf(":"));
part2 = str.subString(str.indexOf(":"), str.length());
result = "{\"" + part1 + "\"" + part2;
Believe something like this could work however you do have to make some assumptions. This is only for a single element so you would have a loop for each item in your string array.

WEIRD: Javascript string.split() and forloop split prepends mysterious comma ',' to resulting string

So I am messing around with JS Objects, trying stuff out. I am taking a GET request, was JSON, now object. I selec the .api path. I want to traverse the object and store it's name so I can pull more JSON for a ORM expirement. Doesn't matter really. But here is the JSON:
var fakeRESTResponse = function() {
return {
"swaggerVersion": "1.2",
"apiVersion": "1.0.0",
"apis": [{
"path": "/Users"
}, {
"path": "/Skills"
}, {
"path": "/Resumes"
}],
"info": {}
};
};
function createSubstr(strin, thechar) {
var substr = [];
for (var i = 0; i < strin.length; i++) {
var str = ' ';
if (strin[i] === thechar) {
console.log("found first match" + strin + ' str[i] ' + strin[i] + ' thechar ' + thechar + ' str: ' + str);
i++;
while (strin[i] !== thechar && strin[i] !== ',' && i < strin.length && strin[i] !== '"') {
if (str === ' ') str = strin[i];
else str += strin[i];
console.log(str + " : " + strin[i]);
i++;
}
substr.push(str);
str = ' ';
}
}
console.log('Return substr ' + substr);
return substr;
}
That was returned from the server. After trying .split, as you will see below, I built a manual function and some weird stuff:
http://codepen.io/willbittner/pen/aObVWG
That code pen above shows the .split('/') function returning the weird objects:
expected: ['Users','Skills','Resumes']
.split: [',Users',',Skills',',Resumes']
Now, if I move the function:
substr.push(str);
str = ' ';
out to the next scope,
**
http://codepen.io/willbittner/pen/GJROEV
**
You get both the for loop and the .split() producing that whack comma.
So I know it has something to do (likely) with the values in the loop changing before they are accessed because I am overlooking something, but I just can't figure out what causes this!!
* Note- I don't want to fix it, so plz don't respond with a different way of doing it. I want to know why this happens. *
To me- if there was a character APPENDED on the end, that would be more acceptable, but what bug in my code PREPENDS a string, as well as SHIFTS it! No Characters were lost! It shifted it as well I guess lol.

How to create an array of variables from an array in Javascript

I have a variable called "information" which creates a multi-dimensional array. For each row in the array, I want to return a variable whose name is the first value in the array. In other words, given the 'information' array below, I'd want the following output:
var lunalovegood = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!;
var dracomalfoy = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Draco Malfoy is a Slythering!;;
var hermionegranger = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Hermione Granger is a Gryffindor!;;
In other words, I want to be able to work with each of the elements in the 'information' array to create some markup. I already know how to get the information I need given the information array, but as you can see below I'd have to declare separate variables for each of the names.
for (var i = 0; i < information.length; i++) {
var htmlString = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!
$('div').html(htmlString);
} //end for loop
var information = [
['lunalovegood', 'Ravenclaw', 'Luna', 'Lovegood', '(chaser)', 'lovegood.jpg', 4]
['dracomalfoy', 'Slytherin', 'Draco', 'Malfoy', '(seeker)', 'malfoy.jpg', 2],
['hermionegranger', 'Gryffindor', 'Hermione', 'Granger', '(none)', 'granger.jpg', 3],
];
The javascript below creates three variables called 'lunalovegood', 'dracomalfoy', and 'hermionegrange', but it's the long way of creating variables. How do I create these variables, one for each row in the array, by looping through the 0th indexed element in the 'information' array?
var myVariables = {}
,varNames = ["lunalovegood","dracomalfoy","hermionegranger"];
for (var i=0;i<varNames.length;i+=1){
myVariables[varNames[i]] = 0;
console.log(lunalovegood);
}
Your current approach just needs a most minor tweak to not require the second array.
var students = {}, i;
for (i = 0; i < information.length; ++i)
students[information[i][0]] = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i][1] + '!';
Now the key is set by taking the first item of the Array. You would then do the following for your text,
students['lunalovegood']; // "Luna Lovegood is a Ravenclaw!"
You're also missing a , in your information literal.
This should help you:
Every variable in the global scope can be accessed as a string property of the window object
var myvariable = 4;
alert(window["myvariable"]); // will alert 4
window["newvariable"] = 6;
alert(newvariable); // will alert 6
I agree with Bergi. Variables should represent a fixed finite set of members defined by code; data (as in the contents of a list) should generally not introduce new variables.
As such, here is the approach I would recommend (note that I've added a bit more than the "minimum required"; good luck!):
// Using a function makes it easy to change details and avoid leaking
// variables accidentally.
function loadWizards(information) {
var wizards = [];
for (var i = 0; i < information.length; i++) {
var info = information[i];
var name = info[0];
// Mapping to named properties means we can forget about indices!
wizards[name] = { // <- use Name to map to our Wizard object
house: info[1],
// ..
image: info[7]
};
}
return wizards;
}
// I have no idea if they are wizards, but give variables useful names.
// 'information' is too generic.
var wizards = loadWizards(information);
// Then later on, use it as:
alert("Hello " + wizards['hermionegranger'].name + "!")
// ^-- property access by Name
var formattedInfo = {};
$.each(information, function (i, v) {
formattedInfo[v[0]] = v[2] + ' ' + v[3] + ' is a ' + v[1];
});
there is a missing comma at the end of the 1st line of your definition of information.
BTW, I like Harry Potter very much.

Categories

Resources