Using String/Array String as Variable name in JavaScript? [closed] - javascript

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
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...

Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

Related

JSON structure in javascript [closed]

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 6 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

Is there a way that this is possible? I am trying to find a value of a var constructed by other variables [closed]

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
This is a little bit of my code. I took out the complex parts. It is all on the script tag.
var trueenemyscoutx = '_2'
var tryeenemyscouty = '2'
var type_22 = "none"
var move1;
enemymove = "type" + trueenemyscoutx + trueenemyscouty;
var move1 = (enemymove.valueOf()).valueOf()
In the post, enemymove is a string constructed by concatenating "type" and two other variables, each of which is also a string.
The resultant string contains no information about the variables used and so the general answer to the question is no, it is not possible using the approach taken.
Obvious alternatives include:
Keep move a string, but use a separator (e.g. colon, comma or space) between component substrings. This allows extracting an array of the components using move.split(separator).
Use an array or simple object to hold move information instead of a string in the first place.

How to use `this` like an object and get its variables/functions by a string? [closed]

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 6 years ago.
Improve this question
I've got an object.
function Obj()
{
}
Obj.prototype.doSomething = function(thing)
{
this["do" + thing]();
}
Obj.prototype.doAlert = function()
{
alert("Alert!");
}
var obj = new Obj();
obj.doSomething("Alert");
This is just a shortened down version of my object, and is a lot bigger.
What I would like to do is that if you pass in 'Alert' it will run this.doAlert(); and if I pass in 'Homework' it will run this.doHomework();
Obviously, in this case, it is stupid to do it like this, but my final project is going to be completely different.
It works fine with window like this:
window["do" + thing]();
but I don't want it to be a global function, but to be part of obj.
Does anyone have an idea how I'd go about doing this?
Thanks in advance!
It turns out that when you get the function through this['functionName'], this is not bound to it.
This means you cannot use this.foo inside any function called like above.
To fix this, I used the following code:
this["do" + thing].bind(this)();
instead of this["do" + thing]();
JSFiddle: https://jsfiddle.net/auk1f8ua/

To understand monkey patching in Javascript [closed]

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 6 years ago.
Improve this question
I am trying to understand the concept behind how monkey-patch works in JavaScript?
I've gone through too many examples but couldn't able to understand
For example - Monkey patching the dispatch function in Redux
let next = store.dispatch
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
Source: http://redux.js.org/docs/advanced/Middleware.html#attempt-3-monkeypatching-dispatch
Can anyone please explain monkey patching in simple terms and example
And which is the best scenarios to use it?
Thanks.
Let say you use a library which define a class Test with a method test.
If you want to monkey patching-it you have to use this kind of code and include it after the library :
// replacing current implementation with a new one
Test.prototype.test = function(arg1, arg2, ...){...}
Now let say you want to do something a bit smarter, like adding something to the function without modifying the rest here is how you would do it :
var oldFN = Test.prototype.test;
Test.prototype.test = function([arguments...]){
[...some custom code...]
oldFN.apply(this, arguments);// arguments keyword refer to the list of argument that your function recevied, if you need something else use call.
[...some custom code...]
}
Monkey patching is valid but must be used wisely. Furthermore each time you upgrade the library, you must check that all your patches works still fine.

creating DOM nodes from arrays [closed]

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
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.

Categories

Resources