I am learning javascript myself. There is a confusion with some javascript,
price = 14;
name = "Mary";
apples:5; //This line executing without error
"orranges":6; //This line getting error
alert(name);
Those both lines can be used into a json object without any error. But when I am using those lines outside of json object, 2nd line ("orranges":6;) is getting error. Why is that ? And why is not giving error for the first line (apples:5;), is there any way that I can use it outside of json object ?
: isn't an operator, it forms part of label syntax.
See MDN
label : statement
labelAny JavaScript identifier that is not a reserved word.
apples is an identifier.
"orranges" is a string literal.
is there any way that I can use it outside of json object ?
You seem to be confusing JSON with object literal syntax.
You can't use a : as the character that separates a property name from a value in an object when you aren't in the process of defining an object.
Related
I am trying to install Trustpilot invitation code on the receipt page of an eCommerce package called Sellerdeck.
I am trying to obtain the customer's name from a variable which I believe is passed from a Perl script.
This variable contains a line break which splits it over 2 lines.
When I try to allocate it to a javascript variable and run it in the browser I get the error:
Uncaught SyntaxError: '' string literal contains an unescaped line break
Is there a way to assign the variable in javascript so that I don't get an error?
I have sorted this via this method where 'InvoiceName' is the variable passed from the perl script:
<div id="sdName" style="display: none;"><actinic:variable name="InvoiceName" /></div>
var tpName = $("#sdName").text();
I'm trying to access a JS variable containing a subset of properties, one of which has an array of values, but while I can access other properties of the same object, I get a jQuery error trying to access the array so there must be something in the syntax causing it to break with the following error:
jquery-1.8.3.min.js:2 Uncaught Error: Syntax error, unrecognized expression: [{"sku":"6104"}]
I've stripped the variable back to the following, but unfortunately I don't have control over the syntax of this variable the live environment, so I'm not sure how to get around this. Essentially this is for extracting data from the variable for use within GTM.
var testLayer = [{
"testProperty": 'test',
"transactionItems": "[{\"sku\":\"6104\"}]"
}];
console.log(jQuery(testLayer[0].testProperty)); // Works
console.log(jQuery(testLayer[0].transactionItems)); // Fails with unrecgnised expression
You probably want to use JSON.parse to access that value:
console.log(JSON.parse(testLayer[0].transactionItems));
JSON.parse turns strings which contain object literals into JavaScript objects.
You could try
console.log(jQuery(JSON.parse(testLayer[0].transactionItems)));
Either if you saying '-' takes as a subtract expression.
eg. Json = {'Me-m':123}
But have you idea why we need to use [] for access this hyphen variable.
Such like that Json['Me-m'].
Writting
Json.Me-m
will evaluate to
Json.Me - m
It will try to access Me property from Json object and subtract m variable, which probably will be undefined.
Because Me-m is not a valid property name to be used as property hence you are forced to use as Maps read this or check here for a valid propert name
That's because '-' has a meaning in javaScript, so if you write Json.Me-m JavaScript interprets: 'Substract the value of the variable m to the value of the attribute Me of the object ``Json`'.
In javascript, you can access any member of an object by name, using [], and inside a string, javascript is not going to try to evaluate anything, so when you write Json[Me-m], it's interpreted as: 'Retrieve the value of the member named Me-m of the object Json'
The reason is simple: in Javascript each object it's an indexed key/value dictionary, accessing to the variable with the "." it's a shortcut, and obviously the fact of the "dictionary object" it's a performance issue, but despite of this matter, javascript it's really fast in comparison with other scripting language.
Answering your question, by desing an index can be a string containing the "-" char, but not a property... so if you have a property with that char, it won't be accessible with the "." notation.
Because you are passing a special character in key part of obj and for accessing that value of obj we need to use [].
eg. json['Me-m']
Im sure this must have been asked before but I can't find an example on SO.
I have a JSON string that starts out life as something like this:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC"},"changed":{"PC":"AC"}}
The string needs to be changed on user input such that "selection" records all the input the user has click on and "changed" is the last thing the user clicks on.
So I have a function that reads the JSON string from a textarea, modifies it dependant on what the user has selected (node and value) and then writes it back to the text area for debugging.
function changeJSON(node, value) {
json = JSON.parse($('#json').val());
json.selection[node] = value;
delete json.changed;
json.changed = {node:value};
$('#json').val(JSON.stringify(json));
}
"selection" works nicely but "changed" updates to the literal variable name I pass it (in this case node) I.e. if I called the function with changeJSON("BC","HC") the JSON string becomes:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC","BC":"HC"},"changed":{"node":"HC"}}
I understand what javascript is trying to do but I want the changed element to be what my variable contains i.e.
,"changed":{"BC","HC"}
and not
,"changed":{"node","HC"}
I'd love someone to tell me what I am doing wrong!?
EDIT
Solved - see below for Quentin explanation as to why and my answer for the code changes necessary - hope it helps others.
I don't think this is the same question, mine is why the literal variable name is used rather than the contents of the variable
The question referenced explains how to resolve the issue, but since you are asking for an explanation.
A variable name is a JavaScript identifier.
A property name in object literal syntax is also a JavaScript identifier (although you can use a string literal instead).
Since an identifier cannot be both a variable and a property name at the same time, you cannot use variables for property names in object literal syntax.
You have to, as described in the referenced question, create the object and then use the variable in square bracket notation.
The solution, as Quentin suggested is to create th object first i.e.
delete json.changed;
json.changed = {};
json.changed[node] = value;
How does one add a variable string in this javascript statement?
where name may correspond to any valid string , say WebkitTransform or Moztransform,etc
document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)';
My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable.
Thanks in advance :)
There are two ways to access members of a Javascript object.
Dot notation, which uses an identifier to access the member:
obj.member;
Bracket notation, which uses a string to access the member:
obj['member']
The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent:
obj[{}]
obj['[object Object]']
If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do:
document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)';
There are 2 ways of accessing values in javascript objects. The first one is by using the dot operator(e.g. object.memberName). The second one is by using the square bracket notation(e.g. object['memberName']).