Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I would like to separate this in Javascript and create variables infos1, infos2 ....
So I need a function to separate all the info.
<option value="[infos1][infos2][infos3][infos4]"></option>
var InfosInitial = $('#insert').find("option:selected").val();
var infos1 = ?;
var infos2 = ?;
Thanks you in advance !
You can use Regex to do this. We will use the String.match() function in this example. It should look something like this:
const InfosInitial = '[infos1][infos2][infos3][infos4]';
const info = InfosInitial.match(/(?<=\[)(.*?)(?=\])/gm);
const infos1 = info[0];
const infos2 = info[1];
const infos3 = info[2];
const infos4 = info[3];
console.log(`${infos1}\n${infos2}\n${infos3}\n${infos4}`);
console.log('As an array:', info);
Also, I am just saying but having everything in 4 different variables is inefficient. So you should use the array instead.
this is really hacky but you can add new variables to the window element like this
window['myVar'] = 'Hello, world!'
now you can call and redefine myVar by simply doing this
console.log(myVar)
// 'Hello, world!'
myVar = 42069
console.log(myVar)
// 42069
knowing this you can create a function where it gets the attribute 'value'
and split it between the ] and [ with String.split() remove the brackets and loop through the remainders
your question little unclear to me but I guess this is what you want.
var InfosInitial = "[infos1][infos2][infos3][infos4]";
Array.from(InfosInitial.matchAll(/\[([^\]]*)\]/g)).forEach(value => {
console.log("all = " + value[0] + ", value = " + value[1]);
})
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Could someone say how to make an array of function names that will change in while loop?
Example of what I want:
var funcNames = ['function1()', 'function2()', 'function3()','function4()','function5()'];
var i = 0;
while( i < funcNames.length ) {
function funcNames[i] {
alert("hello");
}
i++;
}
In the example, the code doesn't work. It only shows how the code should work.
You can think about create new dynamic function name in javascript? like below:
var funcNames = ['function1()', 'function2()', 'function3()','function4()','function5()'];
var i = 0;
var result = [];
while( i < funcNames.length ) {
var funcName = funcNames[i];
var func = new Function("return function " + funcName + "{ alert('hello')}");
result.push(func);
i++;
}
console.log(result);
var firstFunc = result[0]();
console.log(firstFunc()); // invoke one func here
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How to Receive a String in this format: "1-10" and create an array with the amount of numbers in the range. Print the array to screen using a for loop.
I.E - "1-5" received so they array will be: {1,2,3,4,5}
create for workflow with vCenter orchestrator.
You can split the string into array and then iterate in a loop to get the iteration.
let str = "1-5";
str = str.split('-');
for(let i = parseInt(str[0]); i<=parseInt(str[1]); i++) {
console.log(i);
}
You may use some cool ES6:
Array.range = function(s){
const [start,end] = s.split("-");
return Array.from({length:start-end}).map((_,i)=>i+ +start);
};
Usable like this:
Array.range("1-10") //[1,2,3...]
var input = "1-10"; //SAMPE INPUT DATA.
var foo = input.split("-"); //PASRING INPUT DATA.
var answer = [];
for(var i = foo[0]; i<= foo[1]; i++){
answer.push(parseInt(i)); //MAKE AN ARRAY.
}
console.log(answer);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I dynamically create a variable whose name is based on a given string value? For example:
var name = 'jayesh';
var value = 'some value';
// ... do something
console.log(jayesh); // prints 'some value'
You could use an object like this.
var obj = {};
var name = 'jayesh';
obj[name] = 'some value';
var myvalue = obj.jayesh;
You can create a global variable like this:
var name = 'jayesh';
window[name] = 'some value';
You can also use eval but this can cause security issues so use with caution!
var name = 'jayesh';
var evalString = 'var ' + name + ' = "some value"';
eval(evalString);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
wanted some help with a friend's code. We're working on something together, but I'm relatively new to JavaScript. I've included the code below and would like some help understanding the logic. I've understood it for the most part, but not getting the complete picture.
App.SummaryController = Ember.ObjectController.extend({
userExpense: function() {
var userExpenseMap = {}
var expenses = this.get('controllers.expenses');
expenses.forEach(function(expense){
if(userExpenseMap[expense.get('whoPaid')]){
userExpenseMap[expense.get('whoPaid')] += expense.get('amount');
}
else{
userExpenseMap[expense.get('whoPaid')] = expense.get('amount');
}
});
userExpenseList = []
for(var key in userExpenseMap){
var obj = {};
obj.name = key;
obj.expense = userExpenseMap[key];
userExpenseList.push(obj);
}
console.log(userExpenseList);
return userExpenseList;
}.property('controllers.expenses.#each.amount')
});
I'll explain the function, but if you are wanting the ember portion of it that opens a week long class.
userExpense: function() {
// create an object (hash)
var userExpenseMap = {}
// in ember, grab the expenses controller, this shouldn't work, because in order to
// access another controller he should have a needs: ['expenses'] in this controllers hash
var expenses = this.get('controllers.expenses');
//iterate over each expense, named expense in the iteration
expenses.forEach(function(expense){
// if the object hash contains the whoPaid already, increment it by this amount
if(userExpenseMap[expense.get('whoPaid')]){
userExpenseMap[expense.get('whoPaid')] += expense.get('amount');
}
// otherwise create a new person who paid (as the key and set the amount)
else{
userExpenseMap[expense.get('whoPaid')] = expense.get('amount');
}
});
// create a global list (bad practice)
userExpenseList = []
// iterate through all the property names (keys) in the object hash
for(var key in userExpenseMap){
// set obj to a new object/hash (obj is actually hoisted out of here
// so this isn't creating a new variable, just setting obj each time
var obj = {};
//set two properties on it, name and expense with the values from above
obj.name = key;
obj.expense = userExpenseMap[key];
// put it into the global list
userExpenseList.push(obj);
}
// print it out
console.log(userExpenseList);
// return it
return userExpenseList;
}.property('controllers.expenses.#each.amount')
and this is a computed property in ember, that's what the property function at the end is, and the portion on the inside is the dependency, so any time the amount on any instance of an expense which lives on the expenses controller (which is an array) changes the property will be marked as dirty (so if someone is observing it, or depends on it, they will update. The dependency updating etc is Ember Magic, not really Javascript related)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I was hoping someone could point me in the right direction.
I'm basically trying to build an OOP solution to dynamically generate a lot of objects based on a class and then to be able to run methods associated to each object via the class methods.
Below is my un-dynamic code.
// Create videoObject class
function videoObject(videoTag, videoNum){
this.videoTag = videoTag;
this.videoNum = videoNum;
this.videoTagHref = videoTag.attr("href");
this.videoId = function(videoTag){
};
this.addAttrId = function(videoNum){
};
this.printObjectInfo = function(videoId){
};
this.embedVideo = function(videoId, videoTag, videoNum){
};
this.buildControls = function(videoTag){
};
};
// Manually create two objects and run class methods
var newVideo1 = new videoObject($('.yt-player-0'), 0);
newVideo1.videoId();
newVideo1.addAttrId();
newVideo1.embedVideo();
newVideo1.buildControls();
var newVideo2 = new videoObject($('.yt-player-1'), 1);
newVideo2.videoId();
newVideo2.addAttrId();
newVideo2.embedVideo();
newVideo2.buildControls();
// I want to somehow create newVideo1 and newVideo2 dynamically inside a loop like below
var length = $('.yt-player').length;
for (var i = 0; i < length; i++) {
}
Any help you guys could give me would be much appreciated.
Thanks,
Tom
I would try this (untested):
// Create videoObject class
function videoObject(videoTag, videoNum){
this.videoTag = videoTag;
this.videoNum = videoNum;
this.videoTagHref = videoTag.attr("href");
this.videoId = function(videoTag){
};
this.addAttrId = function(videoNum){
};
this.printObjectInfo = function(videoId){
};
this.embedVideo = function(videoId, videoTag, videoNum){
};
this.buildControls = function(videoTag){
};
// call these methods in your constructor instead of repeatedly from elsewhere
this.videoId();
this.addAttrId();
this.embedVideo();
this.buildControls();
// send back a reference to this newly created video object to the loop
return this;
};
// create an array of video object references
var videoObjectReferences = [];
for (var i=0;i<10;i++){
// building ten video objects here, with ids of: yt-player-0, yt-player-1, etc.
// build a selector to reference them via id, not by class with a dot as you have in your question
var sel = String("#yt-player-" + i);
// create the object and store a reference to the video object so you can do something with it later
var newVid = new videoObject($(sel), i);
// build list of references
videoObjectReferences.push(newVid);
}
var videos = [2];
for(var i = 0; i < 2; i++){
videos[i] = new videoObject($('.yt-player-0'), 0);
/*Extra method calls here*/
}
If you always want to initialize your object with those extra method calls, you may want to consider having your object constructor handle that for you. Then your client code would be much cleaner.