filename = "file_1";
name = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);
Expected Result:
file
1
Actual Result:
f
i
http://jsfiddle.net/j667q/1/
I must be doing something wrong, but can't for the life of me work out what.
I have tried:
Using different quotes ' and "
Defining filename and name before using (filename = '';
name = [];)
Spliting using a different character ('-')
Define the array variable first:
var name = [];
DEMO http://jsfiddle.net/j667q/5/
Why this works?
Update for more clarification based on comments:
Although name is not a reserved word, it's a global property of window (eg. window.name and name mean the same), var name; will define a new variable called name which is in another scope and avoids the conflict.
JavaScript Reserved words: http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
The problem is, something to do with global conflicts the global object has a property called name and is somehow conflicting with your code.
rename it http://jsfiddle.net/j667q/3/
you could do var name = ...split... if you don't want to rename it
Yeah, also note, you should ALWAYS declare variables with var there is no reason not to, if you want a global property do window.someName = something;
Declare the variables as var to scope them properly
var filename = "file_1";
var names = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);
name is a js global property. so try not to use it. hope that will help
you have to declare both variables like this.
var filename = "file_1";
var name = filename.split('_');
check out the updated JSFIDDLE (http://jsfiddle.net/prakashcbe/j667q/17/)
Try this...
Other answers all are correct. I don't know your mistake. Anyway, try this as well
[http://jsfiddle.net/puvanarajan/Nytgh/][1]
Related
I just read " Define global variable in a JavaScript function " and I wanted to try to do the same, but this time passing a string as the global variable name.
function createGlobal(strname){
window.strname={
name:"John",
age:27
};
}
createGlobal("myglobal");
//can't use "alert(myglobal.name);", myglobal is not defined and crashes
//however, this works v
alert(strname.name); //John
I am really new to objects, I also tried weird things like window.[strname], window.[""+strname+""] and window.["'"+strname+"'"] without results.
How can I create a global var by passing its name as string?
Try this inside createGlobal:
window[strname] = {name:"John", age:27};
Is it possible to create a new Array, giving it the name of the content of a variable?
For example something like this:
var nameofarray = "array_name";
var ¿nameofarray? = new Array();
So that ¿nameofarray? gets the value of "array_name"?
Assuming you are in global scope (called window) so:
var nameofarray = "array_name";
window[nameofarray] = new Array();
Otherwise it's only posible on objects:
function a() {
var nameofarray = "array_name";
var obj = {};
obj[nameofarray] = new Array();
}
You can also use eval. Which is used for evaluating a string to JavaScript code:
eval('var '+ nameofarray+'=new Array()');
This will work in local scopes as well, but I hardly ever recorment it to anyone.
You would maybe like to read: http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
In PHP and other languages, they are called variable variables. This might help: Javascript "Variable Variables": how to assign variable based on another variable?
If nameofarray is declared in the global scope, you can use the window object:
window[nameofarray] = []; // Use an array literal instead also
^^^^^^^^^^^^^^^^^^^
But you really shouldn't be doing this.
sometime i need to replace a variable value to another
so i use this method
var $$test = "First",
$$test = "Second";
the code work fine but i use jsfiddle JSHint button to check any error on JavaScript (it helped me a lot)
but i got this error '$$test' is already defined
so what is the ideal method to re define any variable
Thank you :)
You're getting that error because you're declaring the same variable twice.
var a = foo, a = bar;
Is the same as:
var a = foo;
var a = bar;
Just break your code in two lines, and you won't get that warning. Like this:
var a = foo;
a = bar;
Also notice that if you declare a variable with a value, and then right after that you change its value, the first line is a noop.
Don't use a comma. You should redefine it as a new statement:
var $$test = 'First';
$$test = 'Second';
this code is trying to define two variable s called $$test. They need to have uniuque names.
Try using $$test1 and $$test2
updated for you http://jsfiddle.net/9CdJN/2/
(function($){
var $$test = "First";
$$test = "Second";
console.log($$test);
})(jQuery);
The problem is that you have a comma , at the end of the first line instead of a semi-colon ;.
Each Javascript statement ends with a semi-colon. You can define multiple variables with a single var by separating them all with a comma.
var var1=1, var2=2, var3=3;
is the same as
var var1=1,
var2=2,
var3=3;
Because you had a comma in the first line, the browser believes you are declaring two different variables with the same name. To fix it, just change it to this:
var $$test = "First";
$$test = "Second";
In PHP we can do this:
$variable = "name_of_variable";
$this->{$variable} = "somevalue";
how to do this in javascript?
where use case should look like:
function Apple(){
var name = "variable_name";
this.(name) = "value";
}
console.log(new Apple());
to output
[Apple: {variable_name:"value"}]
try:
this[name] = "value";
All objects can use dot and array notation for variable access.
Also note, this will allow you to create name value pairs that are inaccessible via dot notation:
var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine
If you are creating a new object literal, you can use string literals for the names for values with special characters:
var foo = {'bar-baz':'fizzbuzz'};
But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:
var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'
Because other answerers are mentioning eval, I will explain a case where eval could be useful.
Warning! Code using eval is evil, proceed with caution.
If you need to use a variable with a dynamic name, and that variable does not exist on another object.
It's important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.
If you need a dynamic variable name within a closure it is better to use a container object:
var container = {};
container[foo] = 'bar';
So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.
var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );
You can use square bracket notation in Javascript:
variable = "name_of_variable";
window[variable] = "somevalue";
You can do this with any object in Javascript.
var name = "var_name";
var obj = {};
obj[name] = 'value';
alert(obj.var_name);
I suggest using associative arrays to do whatever you're trying to do as they are significantly cleaner and easier to debug.
However if you really insist, you can use eval() to accomplish this:
variable = "name_of_variable";
eval(variable + " = \"somevalue\""); // this will work, but please do not do it
alert(name_of_variable);
EDIT: It his just come to my attention that a significantly easier (and better) way of doing this is by simply accessing the window object:
window[variable] = "somevalue";
http://jsfiddle.net/WJCrB/
window['name_of_variable'] = 'somevalue';
or
eval('var ' + variable_name + ' = ' + variable_name + ';');
Beyond that, don't do this. Variable variables are NEVER a good idea and make it nearly impossible to debug problems when (invariably) things break.
This way I could have a function that says whatever_way_you_do_this = something. Is this possible? Basically I could tell a function which variable I want to set by giving it a string that holds the name of the variable.
Thanks
Given:
var x = {
myproperty: 'my value'
};
You can access the value by:
var value = x['myproperty'];
If you're looking for a global variable, then you would check its container (window);
var value = window['x']['myproperty'];
You can use
eval(variableString);
Proceed with caution as many don't recommend using eval()
If it is a global variable named myVar, you can use:
window["myVar"]
The eval function can access a variable from a string containing the variable's name.
eval('baseVariableName'+index) = 'something';