Javascript: String concatenation in object constructor - javascript

Been trying to create a JavaScript object member that always contains a common string. Whenever I create a new object, instead of concatenating the string, it overwrites it with the passed value on creation. If it matters (I don't think it does) the string contains numbers. Par example:
function myObj(strToConcat){
this.combinedString = "Hello " + strToConcat, /* have used + and .concat() without success */
}
var newObj = new myObj("1.2.3");
console.log(newObj.combinedString); /* says "1.2.3", the leading "Hello " is absent */
Can't seem to get this to concatenate the strings.
EDIT: I apologize, the error was outside the code that I thought responsible. Disregard please. My apologies.

You have error in your reference
console.log(myObj.combinedString);
should be
console.log(newObj.combinedString);

Running your code gives me SyntaxError: Unexpected token }. Replace the , at the end of the second line with a ; and I get the expected result of "Hello 1.2.3".

Related

Passing values from JavaServlet to Javascript, calling a Function in Javascript

So there is an old code base I am leveraging from work, currently they are sending over 2 items from an object and I'm adding a third. The third object I'm sending in JAVA as a string, however in the communication over to javascript it's freaking out, I'm getting a horrible error as prototype is declaring it undefined, however I'm watching the code being sent.
Currently the Java code is calling the function. Passing the following data over. All of these are strings.
setCCInfo(xxxxxxxxxxxxxx2205, 1219, 60W76W);
When I remove the final variable, and pass just the first two the function works, however it's almost like prototype is expecting a numeral as I had to change the other two into strings when it got to the front end. I'll attach the code below. The current Error I'm getting is
"prototype-1.6.0.2.js:394 Uncaught SyntaxError: Invalid or unexpected
token
at prototype-1.6.0.2.js:394
at prototype-1.6.0.2.js:635
at prototype-1.6.0.2.js:595
at Array.forEach ()
at Array.each (prototype-1.6.0.2.js:594)
at Array.collect (prototype-1.6.0.2.js:634)
at String.evalScripts (prototype-1.6.0.2.js:394)
at Function. (prototype-1.6.0.2.js:209)
at prototype-1.6.0.2.js:231"
ctx.getResponse().getWriter().print(output.getString("TCResultStatus").toUpperCase());
StringBuilder str = buildJavascriptCall(cceft);
ctx.getResponse().getWriter().print(str.toString());
private StringBuilder buildJavascriptCall(CcEft cceft) {
StringBuilder str = new StringBuilder();
str.append("<script type='text/javascript'>setCCInfo(");
str.append(cceft.getMaskedCCNum());
str.append(", ");
str.append(cceft.getCombinedExpDate());
str.append(", ");
str.append(cceft.getBillingId());
str.append(");</script>");
return str;
}

Why does a string literal beside an array like this not throw a syntax error in javascript?

During my coding I made a mistake by calling a function like this
someFunction( 'abc' [someValue] )
I had forgotten the colon inside the function call.
After I found the error I played around.
An assignment like this does not throw an error as well.
let a = 'abc'[someValue];
I would expect a syntax error here. Is there an explanation for this?
A string in Javascript can behave as an object and, as such has properties such as .length and methods such as .slice. So, for any property access on an object in Javascript, one can use either the dot notation as in:
str.length
or the [] syntax as in:
str["length"]
or using a variable:
let len = "length";
str[len]
So, what you have with:
'abc' [someValue]
Is just that syntax. A string followed by a property access. That is legal Javascript. It attempts to get the property from that object with the name of whatever string is in the someValue variable.
Here's are a couple working examples:
// simple property access
let prop = "length";
console.log("abc"[prop]);
// method call
console.log("one fine day"["slice"](4, 8));
One would not generally code this way with a string, but it's perfectly legal as it's just part of how one can access properties on an object in Javascript.
Because that's not a syntax error. The engine thought you were trying to get a letter from that string, so if someValue was a number it will work perfectly fine
let a = "abc"[0]
console.log(a, "abc"[1]) //a, b

JSON Parsing in AngularJS Service

I have Angular service and in that service I have a code:
this.testMethod = function( ) {
this.jsonTest = "[{'id':'123','title':'XYZ','id2':'456','status':2}]";
this.parseTest(this.jsonTest);
};
this.parseTest = function(jsonTest) {
var jsonTestObj = JSON.parse(jsonTest); // I get error hear
}
Test method is getting called on ng-click event.
Error that I am getting while testing in latest chrome browser:
SyntaxError: Unexpected token ' at Object.parse (native)
......
I tried multiple things to fix it but nothing seems to work.
Every time I get undefined value error.
Basically I want to parse JSON object and get the values.
What am I doing wrong?
Use this
this.jsonTest = '[{"id":"123","title":"XYZ","id2":"456","status": "2"}]';
Or this
this.jsonTest = "[{\"id\":\"123\",\"title\":\"XYZ\",\"id2\":\"456\",\"status\": \"2\"}]";
You either need to use ' outside or " outside and escape the quotes inside.
Both the key and value need to be in double quotes.
You need to use double quotes in your string, other than that your code should work.
To quote from specification
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Your JSON is not valid. Always check your JSON integrity in those cases, i personaly use
http://jsonlint.com/

Accessing an array by index within an object

I'm trying to access a particular array by it's index within an object within an object (sorry, this may be the wrong terminology).
var person = {
name: ["Tom", "Mike", "Sally"],
hair: {
style: ["bob", "weave", "mullet"],
length: ["long","short","medium"]
}
}
getDetail(length);
function getDetail(det) {
var answer = person.hair.det[1];
console.log("Hair " + det + " is " + answer) //outputs: "Hair length is long"
}
When I do this, I am getting an error of "Can't read property '1' of undefined". Which tells me it isn't passing the 'det' variable correctly. If I take that out and put length instead, it works.
What am I missing?
Thanks!
The problem is that in your case you should be passing a string or a variable to your getDetail() function (length by itself is none, as it is not defined previously, nor is quoted), also there's the fact that if you want to use a variable to indicate the property/key of an object, you should use this type of syntax: object["property"]. You can change your code to:
getDetail('length');
function getDetail(det) {
var answer = person.hair[det][1];
console.log("Hair " + det + " is " + answer) //outputs: "Hair length is long"
}
When you say getDetail(length), that's looking for a variable called length, and passing it into the function. Since it doesn't exist, the function gets undefined.
HOWEVER, when you write "myObjectVariableName.etcetera", it will specifically look for an index called "etcetera" - so it won't even be using your det argument - it's instead looking for the "det" index.
You can, instead, write either of the following.
myObjectVariableName["myIndexName"]
var myString = "myIndexName";
myObjectVariableName[myString]
Both of those will both have the same result.
So, to get the expected result, what you want to do is pass the string "length" into getDetail, and then replace .det with [det] (darkajax seems to have written what I was going for, but I'm hoping my explanation also helps make sense of why it wasn't working)

Viewing an object

I am learning JS and after fiddling around with adding elements etc I tried to do an alert() with the object but instead got this error: [object htmltableelement]
so I then tried:
alert(t.toString());
and got the same error... how can I see the contents of the object?
you can use firebug:
console.log(t);
or you can use innerHTML;
alert(t.innerHTML);
The way I normally do this is by using FireBug firefox add-on.
Add a break point in your JavaScript then you can view any object and all its keys/values.
See everything:
for(var key in t)
alert('key:' + key + ', value: ' + t[key]);
You may want to replace alert with console to avoid 100s of alerts
function domObjectToString(domObject){
if(typeof(domObject) ==='object'){
var divElement = document.createElement('div') ;
divElement.appendChild(domObject);
return divElement.innerHTML;
}else{
return domObject.toString();
}
}
---- steps follow -----
1. check the domObject Type [object]
2. If Object than
a. Create an "Div" element
b. append DomObject To It
c. get The innerHTML of the "div" it Gives The String
3. If Not an Object than convert to String and return it .
That is not an error. That is the default string representation of an object.
Either iterate through the object's properties and output them one by one, or use a proper debugging tool like Firebug that'll give you the ability to really examine your variables.

Categories