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
When i execute the following script the alert statement is printing the function why is it so?
What happens in the execution context? Why the variable basicPattern's undefined value is not printing?
function basicPattern(){
var o = 5;
return o;
}
var basicPattern;
console.log(basicPattern);
function basicPattern(){
var o = 5;
return o;
}
var basicPattern;
console.log(basicPattern);
Evaluates same as this (IE bugs disregarded):
var basicPattern;
basicPattern = function basicPattern(){
var o = 5;
return o;
};
console.log(basicPattern);
Since basicPattern was already declared, declaring it again won't have any effect since declarations
are hoisted and merged. If you had assignment to 5 it would go like this:
var basicPattern;
basicPattern = function basicPattern(){
var o = 5;
return o;
};
basicPattern = 5;
console.log(basicPattern);
Read more about hoisting: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
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
I have written some javascript code using the IIFE, here I have stored a variable x in a function item1 inside the IIFE hidden. Now I want to create another function, say item2 and I want to use the variable x inside this new function. And how exactly do I do this?
var hidden = (function () {
var item1 = function () {
x = 5;
}
})();
x can be a variable in your iife so it acts like a private variable while you only expose the closures item1 and item2.
Below is a simple example:
var hidden = (function(){
var x;
var item1 = function(){
x=5;
}
var item2 = function(){
return x;
}
return {
item1: item1,
item2: item2
}
})();
hidden.item1()
console.log("value of x", hidden.item2())
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I have a 'render' function:
render: function(playerId){
this.getTotalPoints(playerId);
// and some other code after this;
}
This 'render' function may be executed with or without a playerId. This is the getTotalPoints function:
getTotalPoints: function(playerId){
if(playerId){
this.allplayers[playerId].totalPoints = this.calculatePoints(this.allplayers[playerId].cards);
}else{
this.allplayers.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
}
And the third function that actually calculates the points
calculatePoints: function(cards){
points = 0;
for( var i = 0; i < cards.length; i++){
points+=cards[i].points;
};
return points;
}
I am repeating myself in getTotalPoints, where I have a call to this.calculatePoints - one for a single player and then one for all the players, depending on whether the playerId is set or not.
Is there any chance I can avoid this and simplify the code?
I would do something like:
getTotalPoints: function(playerId){
var selected = playerId ? [this.allplayers[playerId]] : this.allplayers;
selected.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
However, since you're changing the state of the players, I would not call the function getTotalPoints, maybe computeTotalPoints?
I see two different functions: calculatePointsForPlayer and calculatePointsForPlayers. Second function will call first function.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need to go from
'IsEditOnly=False;IsLastFieldInRow=False;IsReadOnly=False;Title=bedrijfStandaard;Width=100'
to something like
{IsEditOnly: false, Title: 'bedrijfStandaard'}
Thanks
var s='IsEditOnly=False;IsLastFieldInRow=False;IsReadOnly=False;Title=bedrijfStandaard;Width=100';
s=s.replace(/=/g, ':"');
s=s.replace(/;/g, '",');
s+='"';
eval('var obj={'+s+'}');
alert(obj.Width);
http://jsfiddle.net/w1yq4vtc/
You could try this:
var queryToObject = function(s){
var
i = 0,
retObj = {},
pair = null,
qArr = s.split(';');
for (; i < qArr.length; i++){
pair = qArr[i].split('=');
retObj[pair[0]] = pair[1];
};
return retObj;
};
var query = 'IsEditOnly=False;IsLastFieldInRow=False;IsReadOnly=False;Title=bedrijfStandaard;Width=100';
console.dir(queryToObject(query));
JSFiddle
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
var makeModelYearSelect = document.getElementById("<%= MakeModelYearFilterLB.ClientID %>").control;
var selectedMakeModelYearItems = makeModelYearSelect.get_checkedItems();
var selectedMakeModelYearItemIds = [];
for (var index = 0; index < selectedMakeModelYearItems.length; index++) {
selectedMakeModelYearItemIds.push(selectedMakeModelYearItem[index].get_value(index));
}
Why is this firing back an error of Microsoft JScript runtime error: 'selectedMakeModelYearItem' is undefined?
Mootools won't let me use a simple for...in for iterations.
I've looked at it 6 ways to Sunday so what the heck am I missing?
Because selectedMakeModelYearItem is undefined.
selectedMakeModelYearItems isn't, though.
Maybe you try to call this code berofe page is loaded. In this case select tag that you try to access don't rendered and cannot be accessed from JavaScript. You can try something like
window.addEventListener("load",
(function() {
return function setMakeModelYearFilter() {
var makeModelYearSelect = document.getElementById("<%= MakeModelYearFilterLB.ClientID %>").control;
var selectedMakeModelYearItems = makeModelYearSelect.get_checkedItems();
var selectedMakeModelYearItemIds = [];
for (var index = 0; index < selectedMakeModelYearItems.length; index++) {
selectedMakeModelYearItemIds.push(selectedMakeModelYearItem[index].get_value(index));
}
window.removeEventListener('load', setMakeModelYearFilter, false);
}})()
, false);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometimes you have a function that will work for flat arguments. For example:
send(player,message)
But what if, instead, you have collections of players / messages?
message = ['Welcome!','Check our site for events.']
players = [Player1,Player2,Player3]
Writting for-loops will reduce readability and won't work if you don't know statically if your argument is a collection or object. Rewritting the function is sometimes not viable or too laborous and promotes duplicate code. What is a simplier solution?
You can write a decorator that will transform your function into a function that will take the cartesian product of it's own arguments and call the original function on it.
function send(player,message) {
console.log('To ',player,': ',message);
}
cartesian(send)(['Player1','Player2','Player3'],['Welcome!','Check our site.']);
//Output:
//To Player1 : Welcome!
//To Player1 : Check our site.
//To Player2 : Welcome!
//To Player2 : Check our site.
//To Player3 : Welcome!
//To Player3 : Check our site.
This implements the decorator ("cartesian") on Javascript:
function cartesian_product(arr){
//cartesian_product( [[1,2],[3,4]] ) = [[1,3],[1,3],[2,3],[2,4]]
function partial_product(arr,i){
//partial_product([[1,2],3],0) = [[1,3],[2,3]]
var result = []
for (j=0; j<arr[i].length; ++j){
arr_changed = arr.slice();
arr_changed.splice(i,1,arr[i][j]);
result.push(arr_changed);
};
return result;
};
var result = [arr.slice()];
for (var x=0; x<arr.length; ++x){
for (var y=0; y<result.length; ++y){
if (result[y][x] instanceof Array) {
result.splice.apply(result,[y,1].concat(partial_product(result[y],x)));
}
}
}
return result;
};
function cartesian(func){
//cartesian(func)([1,2],[3,4]) = [func([1,3]),func([1,4]),func([2,3]),func([2,4])]
_this = this;
return function(){
var args_list = cartesian_product(Array.prototype.slice.call(arguments));
var return_values = []
for (var i=0; i<args_list.length; ++i){
return_values.push(func.apply(_this,args_list[i]))
}
return return_values;
}
}