I've looked at multiple questions in search for an answer however to no avail, I'm trying to obtain the variable from a parent function and passing it like "a(b)" doesn't seem to work
I cannot for the life of me obtain 'item_classes', is there another way in which I can write my code in order for it to be operable
$(document).ready(function () {
$('.nm-more').hover(function () {
var item_num = $(this).data('stg-id');
var item_names = $(this).data('stg-items');
var item_classes = $(this).data('stg-class');
item_names.forEach(function (entry) {
var item_index = item_classes[entry];
alert(entry + ' ' + item_index);
});});
});
});
Here is a jsfiddle http://jsfiddle.net/bgzkge65/25/
Problem solved:
http://jsfiddle.net/bgzkge65/27/
$(document).ready(function () {
$('.nm-more').click(function () {
var item_num = $(this).data('stg-id');
var item_names = $(this).data('stg-items');
var item_classes = ($(this).data('stg-class'));
item_names.forEach(function (entry) {
var item_index = item_classes[item_names.indexOf(entry)];
alert(entry + ' ' + item_index);
});
});
});
And HTML changes:
<li class="nm-more" data-stg-id="2" data-stg-items='["Mark as read", "Mark as unread", "Flag all items", "Unflag all items"]' data-stg-class='["readit", "unreadit", "flagit", "unflagit"]'>Mark all</li>
<li class="nm-more" data-stg-id="1" data-stg-items='["Mark as read", "Mark as unread", "Flag items", "Unflag items"]' data-stg-class='["readit", "unreadit", "flagit", "unflagit"]'>Selected</li>
What I did:
First of all: data-stg-class wasn't formatted as an array. I reformatted and made it an array.
The code was actually correct, but you are using named keys, but you need to use indexes here. So entry should be an index and not a reference to a named key from data-stg-class. So I used item_names.indexOf(entry) to retrieve the proper index and return the correct value.
Instead of array.indexOf, you could also retrieve the index from forEach. It's the second argument of that function, either declare it in the function declaration or retrieve it with arguments[1]. In this case the indexes of both arrays match which makes this alternative solution viable.
Related
ok I am trying to answer a question and learning to code. regarding an array and using foreach statements the function must remain as this "function animalNames" must stay somewhere but apparently, I am doing something wrong because I get it returned as undefined. even through it produces the correct array back could someone look at it and let me know what i have done wrong.
attached is a picture of the code and array and question that i answered. this is how i wrote my function.
const displayNames = [];
zooAnimals.forEach(function animalNames(element){
var display = "name: " + element.animal_name + ", " + "scientific: " + element.scientific_name
displayNames.push(display);
})
console.log(displayNames);
again i get the correct array back and the data looks correct...but animalNames comes back as undefined...i cannot remove this portion i am to keep it there but i do not know what to do with it.
try this, it defines a function animalNames as separate function
const displayNames = [];
const zooAnimals = [
{animal_name:"Jackel",scientific_name:"Canine"}
]
function animalNames({animal_name, scientific_name}){
return `name: ${animal_name}, scientific: ${scientific_name}`
}
zooAnimals.forEach((element)=>{
displayNames.push(animalNames(element));
})
console.log(displayNames);
I believe you are following this challenge. In this case, make sure to read the instructions properly:
The zoos want to display both the scientific name and the animal name in front of the habitats.
Use animalNames to populate and return the displayNames array with only the animal name and scientific name of each animal.
displayNames will be an array of strings, and each string should follow this pattern: "name: {name}, scientific: {scientific name}"
So from the instructions you are expected to create a function animalNames() that creates an array named displayNames and returns this array from within your function animalNames(). The array displayNames contains strings of the sturcture name: animal_name, scientific: scientific_name.
// you could set zooAnimals as a required parameter in your function
// but as it is defined in the same file you can access it directly as well
function animalNames() {
const displayNames = [];
// you have to do the forEach on zooAnimals here
zooAnimals.forEach(animal => displayNames.push(`name: ${animal.animal_name}, scientific: ${animal.scientific_name}`))
// return an array
return displayNames;
}
The way you did it, the function animalsName() is an anonymous function that only exists within the zooAnimals.forEach() call. Therefore, it is undefined.
I am coding for a server of RAGEMP and I'm getting the following error:
animais.indexOf is not a function
Here's a simplified version of my code:
var animaisNomes = ["falcao", "golfinho", "gato", "vaca", "javali", "macaco", "coiote", "veado", "orca", "rato", "cao", "puma"];
var animaisIDs = ["a_c_chickenhawk", "a_c_dolphin", "a_c_cat_01", "a_c_cow", "a_c_boar", "a_c_chimp", "a_c_coyote", "a_c_deer", "a_c_killerwhale", "a_c_rat", "a_c_retriever", "a_c_mtlion"];
mp.events.addCommand('animal', (player, fullText, animal) => {
index = animais.indexOf(animal)
player.outputChatBox(String(index))
});
After i typed the command /animal [some animal] it should return me the index of where that animal is in the list, but instead it returns me the error. Why?
Here's the full code
var animaisNomes = ["falcao", "golfinho", "gato", "vaca", "javali", "macaco", "coiote", "veado", "orca", "rato", "cao", "puma"];
var animaisIDs = ["a_c_chickenhawk", "a_c_dolphin", "a_c_cat_01", "a_c_cow", "a_c_boar", "a_c_chimp", "a_c_coyote", "a_c_deer", "a_c_killerwhale", "a_c_rat", "a_c_retriever", "a_c_mtlion"];
mp.events.addCommand('animal', (player, fullText, animal) => {
if (animaisNomes.includes(animal)) {
player.outputChatBox("Inclui")
index = animais.indexOf(animal)
player.outputChatBox(String(index))
}
else {
player.outputChatBox("Esse animal não está disponível.")
}
});
In the 7th line of the full code version, you wrote animais instread of animaisNomes.
Do index = animaisNomes.indexOf(animal) and it should work.
var animals is an object, the curly braces denotes an object {} in javascript.
indexOf would work for arrays and not objects.. arrays are denoted by []. So when you use this function on object it would not work. I would suggest you convert it to an array of objects like this..
var animais = [
{'falcao': "a_c_chickenhawk"},
{'golfinho': "a_c_dolphin"},
]
in this way you would be able to use indexOf but you would need to make changes to accomodate these key value pairs..
I have a variable being set as the .html(); of a <div />
The variable is the name of another variable. I want it to display the contents of the other variable, however it simply displays the name of the other variable.
How can I force it to show the variable contents rather than just a literal text string?
var clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store';
setInterval( function() {
var term = $("input").val();
$("#results").html(term);
}, 100);
When the user types 'clothing' into $("input"); the contents of the 'clothing' variable should be displayed in the $("#results"); <div />. Instead it just says 'clothing'.
Another way is to use object properties, like this
var obj = {};
obj.clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store';
setInterval( function() {
var term = $("input").val();
$("#results").html(obj[term]);
}, 100);
Here's the fiddle: http://jsfiddle.net/ZL7EQ/
The only way I know how to solve this is using eval:
$("#results").html(eval(term))
But you really shouldn't want to do that. :)
Use a dictionary.
// store strings in an object so you can look them up by key
var dict = {
clothing: 'dogeshop ...',
anotherKey: '...'
};
// update the result when the input changes
$('input').on('change', function() {
var result = dict[this.value]; // make sure the key exists
if (result) {
$('#results').val(result); // update the results
}
});
I use to make this mistake myself when working with jQuery.
Try instead:
$("#results").text(term);
Not sure what you have the interval for. You could just change the #results with a change event.
I have an list of values like this from a sql database.
UserName Email ComputerName DateIssued
jjsmith jjsmith#example.com JTComputer 9/14/2013
ltjoseph ltjoseph#example.com LTComputer1 10/21/2013
KTsmith KevinTem#example.com KTComputer1 01/25/2012
ltjoseph ltjoseph#example.com LTComputer2 01/11/2013
KTsmith KevinTem#example.com KTComputer2 01/25/2012
I transform my list into an array of objects.
var user_array = [
{"username":"jjsmith", "email":"jjsmith#example.com", "computerName":"JTComputer", "dateissued":"10/21/2013"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer1", "dateissued":"10/21/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer1", "dateissued":"01/25/2012"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer2", "dateissued":"01/11/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer2", "dateissued":"01/25/2012"}]
A function has been created by someone else that sends emails to users, it only accepts two parameters which are strings.
So I don't want to send more than 1 email per user. So I am trying to figure out how to combine the items together so that my an example set of strings look like this.
var str1 = "ltjoseph#example.com";
var str2 = "ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013";
and then fire the other user function to send emails for each of the items in the list.
function sendEmails(str1, str2);
If anyone has any ideas how i can do this. Please advise..
var by_user = {};
for (var i = 0; i < user_array.length; i++) {
if (by_user[user_array[i].username]) {
// Found user, add another computer
by_user[user_array[i].username].str2 += ', ' + user_array[i].computerName + '-' + user_array[i].dateissued;
} else {
// First entry for user, create initial object
by_user[user_array[i].username] = {
str1: user_array[i].email,
str2: user_array[i].username + ', ' + user_array[i].computerName + '-' + user_array[i].dateissued
};
}
}
Now you have the by_user object, which has a single sub-object for each user, whose str1 and str2 properties are the variables you want.
by_user['ltjoseph'].str1 => ltjoseph#example.com
by_user['ltjoseph'].str2 => ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013
something like this:
var str1=array[0].email
var str2=array[0].username+", "+array[0].computerName+array[0].dateissued
or use a loop and iterate through the array
I strongly recommend bringing in a library like lodash for this sort of thing and using uniq (sample here: http://jsfiddle.net/MwYtU/):
var uniqs = lodash(user_array).pluck('email').uniq().value();
If you're doing javascript and aren't acquainted with lodash or underscore, go do that because it'll save you a lot of time. Using tried and true code is a good idea. Added bonus: if you want to see how the pros are doing something like uniq you can just look at the source code.
I'm new to JSON and mustache. I'm trying to iterate an array that I've created using Mustache and I'm running into some issues. My code looks like this:
var shows=[
{"title":"Strawberry Shortcake","description":"A show about a cake","video":"none","category":"chilren"},
{"title":"Vanilla Ice","description":"A show about a ice","video":"none","category":"adult"}
];
var template="{{#shows}}{{.}}{{/shows}}";
var html=Mustache.render(template,shows);
document.write(html);
You want "shows" to be in a hash in order to properly iterate:
var shows={"shows":[
{"title":"Strawberry Shortcake","description":"A show about a cake","video":"none","category":"chilren"},
{"title":"Vanilla Ice","description":"A show about a ice","video":"none","category":"adult"}
]};
var template="{{#shows}}{{.}}{{/shows}}";
var html=Mustache.render(template,shows);
document.write(html);
This will have the desired effect of producing your template multiple times.
UPDATE
To your question on Lambdas. I just looked this up in the manual. I think it covers what you were asking about:
When the value is a callable object, such as a function or lambda, the
object will be invoked and passed the block of text. The text passed
is the literal block, unrendered. {{tags}} will not have been expanded
- the lambda should do that on its own. In this way you can implement filters or caching.
Template:
{{#wrapped}}
{{name}} is awesome.
{{/wrapped}}
Hash:
{
"name": "Willy",
"wrapped": function() {
return function(text) {
return "<b>" + render(text) + "</b>"
}
}
}
u can do like this:
var shows=[
{"title":"Strawberry Shortcake","description":"A show about a cake","video":"none","category":"chilren"},
{"title":"Vanilla Ice","description":"A show about a ice","video":"none","category":"adult"}
];
var template="{{#.}}title:{{title}},video:{{video}}{{/.}}";
var html=Mustache.render(template,shows);
document.write(html);