JS: Including a variable name into another variable name possible? - javascript

So for example I am trying to do a for loop in JS
for (var i=0;i<result.length;i++){
var btn[i] = document.createElement("BUTTON");
var t[i] = document.createTextNode("CLICK ME");
btn.appendChild(t[i]);
}
the i being the delimiter, is it possible to append it to another variable name like above when I try to create an element? Just to make the variable name unique. Right now I am trying with the square brackets and it's giving me an error saying unexpected []. Any help is appreciated thanks!

In browsers (I've never done any node.js stuff) the global scope lives in the window object.
bla = 'test';
window['bla'] == 'test';
This means that you can create a variable say test1 like this:
window[bla + 1] = 'foo';

Related

replace the text of a variable

I am trying to replace the text from one variable to another but this tells me: newLinkRef is not defined
<script>
$('.sous_img_montureCard').click(function(){
var idMiniatureRef = $(this).attr('id');
var linkRef = $(this).parents('.montureCard').children('.CardReferenceEnvies').children('.divCardRef').children('.sousDivCardRef').children('p');
newLinkRef.replace(linkRef, idMiniatureRef);
$(this).parents('.montureCard').children('.CardReferenceEnvies').children('.divCardRef').children('.sousDivCardRef').children('p').html(newLinkRef);
});
</script>
I had succeeded with
var newLinkRef = linkRef + idMiniatureRef;
but that adds [OBJECT OBJECT]3CLA02A
and I just want 3CLA02A
It's because you haven't defined newLinkRef before. Define it, then replace.
As the error says, newLinkRef is not defined. define it with var, set a value to it, and then you can call .replace() or any other method on it.
I just found my concern, it was simply:
var newLinkRef = idMiniatureRef;
I was absolutely looking to put a replace () x)

What's wrong with this var statement declaring a variable with a dot in the name?

I'm new to JavaScript and I get an error saying that my code is missing semicolons on line 2. What semicolons does it need? I already put semicolons.
var success = function(){
var wx.varx = $scope.vr;
$state.go("/there");
};
The problem with that line is that it's simply invalid. The error message is just the parser doing its best to figure out what's going on.
var declares a variable. Literal variable names (IdentifierName in the spec) cannot contain a ..
If you have an in-scope wx identifier referencing an object and want to set a property on it, remove var:
wx.varx = $scope.vr;
If you want to create a new variable, remove the . from the name.
var wxvarx = $scope.vr;
If you want to create a wx variable and an object containing varx as a property:
var wx = {
varx: $scope.vr
};
Use like this
var wx={};
wx.varx = $scope.vr;
You cannot use variable directly as an object
You cannot declare an object property directly using
var wx.varx
As the object does not exist at this point. Instead you need to declare the object (wx) and set varx.
var vx = {
varx: $scope.vr
};

Iterate string array error, runs for first item's letters

I have a simple array loop, runs perfect in jsFiddle showing all items, see https://jsfiddle.net/8odoros/b27ocs4d/1/
What's strange is that putting the same script here as a snippet runs by letter, showing the first string letter by letter. I feel stupid, am I missing something? Check it out:
var name = ['Helen','Jim','Thomas','Luke','Theodore'];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
var newHtml = name[i]+' '+i+'</br>';
div.innerHTML = div.innerHTML + newHtml;
}
<div id="cards"></div>
Word name is a reserved word (as #prasad answered) in javascript that why your code was not working as expected.
See below code, after changing name with names. Its seems working as was working in jsfiddle.
var names = ['Helen','Jim','Thomas','Luke','Theodore'];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
var newHtml = names[i]+' '+i+'</br>';
div.innerHTML = div.innerHTML + newHtml;
}
<div id="cards"></div>
Note: name can only be used as local variable inside a function or iife and can not used as global varibale.
Try any one of the function its working. name is reserved word of javascript.But applied with in function .Its not act as a reserved word.This is one of the way preventing the action.
(function () {
var name = ["Helen","Jim","Thomas","Luke","Theodore"];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
var newHtml = name[i]+' '+i+'</br>';
div.innerHTML = div.innerHTML + newHtml;
}
})()
<div id="cards"></div>
Apparently name is a property of window and it has a setter which converts the input value to a string. Your code is trying to assign an array to that property which is magically converted to a string:
var name = ["foo", "bar"];
console.log(name); // array converted to "foo,bar"
So why does it work on jsFiddle? The answer is that, by default, jsFiddle wraps your code inside a function, something like this:
<script>
window.onload = function() {
var name = ["foo", "bar"];
console.log(name); // ["foo", "bar"]
}
</script>
This creates a closure where var name creates a new variable instead of referring to window.name. If you change your jsFiddle settings (JavaScript tab > Load type > No wrap - in body) then you get the same result as the StackSnippet like this:
<script>
var name = ["foo", "bar"];
console.log(name); // "foo,bar"
</script>
The solution is not to pollute the global namespace in the first place. That way you do not have to lookup the list of "words not to use as JavaScript variables".
name AKA window.name
Well name is most definitely not a reserved word in javascript.
name AKA window.name is the name of the window. Its value is set by a setter function and as the window name should be a string. So when you set it with name=["foo","bar"] it is converted to a string.
It is unfortunate that Javascript must share the global name space with every man and his dog and this illustrates another reason to avoid the global scope whenever possible.

Javascript: How to dynamicly add a number to a variable name?

Say I have to following code:
var numb = $(selector).length;
And now I want to dynamicly make variables based on this:
var temp+numb = ...
How would I be able to do this?
Edit:
I know some of you will tell me to use an array. Normally I would agree but in my case the var is already an array and I rly see no other solution than creating dynamic names.
Variables in Javascript are bound to objects. Objects accept both . and [] notation. So you could do:
var num = 3;
window["foo"+num] = "foobar";
console.log(foo3);
PS - Just because you can do that doesn't mean you should, though.
In global scope (not recommended):
window["temp"+numb]='somevalue;
window.console && console.log(temp3);
In a scope you create - also works serverside where there is no window scope
var myScope={};
myScope["temp"+numb]="someValue";
window.console && console.log(myScope.temp3);

Object arrays in JavaScript

If I do this,
var element = {};
alert(element);
element[name] = "stephen";
alert(element.name);
Why doesn't element.name work?
When using bracket notation, (unless it's a variable) it needs to be in qoutes, like this:
var element = {};
alert(element);
element["name"] = "stephen";
alert(element.name);
You cant test it out here. To explain what I mean by "unless it's a variable", this would also work:
var myVariable = "name";
element[myVariable] = "stephen";
Because name should be in quotes.
This works:
var element = {};
alert(element);
element['name'] = "stephen";
alert(element.name);
Try it.
This is the reason why you may want to get an object's property dynamically. For example:
You have a variable, but you can't be sure of its value. The server send you the variable value so you should write like this.
obj[name].age // Here the name is a variable, and it can be changed in every page refresh, for example.
But if you want to set obj['name'] = 'Lorenzo' you have to use quotes.
Think like obj[name] is used for set, obj['name'] is used for get.

Categories