This question already has answers here:
How to access a numeric property?
(3 answers)
Closed 4 years ago.
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';
var obj = JSON.parse(s);
document.getElementById("user").innerHTML =
"Name: " + obj.1 + " " + obj.2 + "<br>" +
"Location: " + obj.3;
Error from console:
Uncaught SyntaxError: Unexpected number
Use bracket notation to access numeric keys of an object:
const obj = { "1": "Sammy" };
console.log(obj["1"]);
Same goes for using some other character, for example -:
const obj = { "test-123": "works only with bracket notation" };
console.log(obj["test-123"]);
As gurvinder372 suggests, identifier cannot be numeric, you tried to access object's property with a number, which is wrong.
Correct Code
var s = JSON.parse('{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}');
document.getElementById("user").innerHTML =
"Name: " + s["1"] + " " + s["2"] + "<br>" +
"Location: " + s["3"];
you cannot have numbers after . (dot operator)
you should try using [].
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';
var obj = JSON.parse(s);
document.getElementById("user").innerHTML =
"Name: " + obj[1] + " " + obj[2] + "<br>" +
"Location: " + obj[3];
Related
I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}
I have some of this Code:
function writeIslamicDate(adjustment) {
var wdNames = new Array("Ahad","Ithnin","Thulatha","Arbaa","Khams","Jumuah","Sabt");
var iMonthNames = new Array("Muharram","Safar","Rabi'ul Awwal","Rabi'ul Akhir",
"Jumadal Ula","Jumadal Akhira","Rajab","Sha'ban",
"Ramadan","Shawwal","Dhul Qa'ada","Dhul Hijja");
var iDate = kuwaiticalendar(adjustment);
var outputIslamicDate = wdNames[iDate[4]] + ", " + (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " AH";
return outputIslamicDate;
}
document.write(writeIslamicDate());
Output : Ithnin, 23 Ramadan 1435 AH
?
I want to replace 23 with bengali number ২,৩ ///// or two, three
I watch and try a lot of but couldn't success.. Is there are any to solve this ?
Thanks.
I do like
var someString = (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " হিজরী";
var outputIslamicDate = somestring.replace(/1/g, "১").replace(/4/g, "৪");
return outputIslamicDate;
but it's not work...
Use regex and the global flag:
str.replace(/word/g, 'word2');
I'm trying to get the var dir= director to refer to the property "director":"Jean Rouch and Edgar Morin.", How can I do that? I'm new to Javascript, so pardon me if I don't use the right terms.
var myFavoriteDocumentary = {
"name": "Chronicle of a Summer.",
"reldate": "1961.",
"language": "French.",
"director": "Jean Rouch and Edgar Morin.",
"getFavFilm": function () {
return "My favorite non-fiction film is:" + "\n" + this.name + "\n" + "Directed by:" + "\n" + this.director + "\n" + "Year of film:" + "\n" + this.reldate + "\n" + "Language:" + "\n" + this.language;
}
}
console.log(myFavoriteDocumentary.name);
console.log(myFavoriteDocumentary.getFavFilm());
var dir= "director"
function dirFake(dir) {
console.log("The directors are: " + dir);
dir = "Vertov";
console.log( dir + " is not the director" );
}
dirFake(dir);
console.log( dir + " are the true directors!" );
You can use same procedure that you use to console name.
var dir=myFavoriteDocumentary.director;
If you're asking what I think you're asking, just use javascripts bracket or dot notation for objects.
myFavoriteDocumentary.directory;
myFavoriteDocumentary["directory"];
var myFavoriteDocumentary = {
"name": "Chronicle of a Summer.",
"reldate": "1961.",
"language": "French.",
"director": "Jean Rouch and Edgar Morin.",
"getFavFilm": function () {
return "My favorite non-fiction film is:" + "\n" + this.name + "\n" + "Directed by:" + "\n" + this.director + "\n" + "Year of film:" + "\n" + this.reldate + "\n" + "Language:" + "\n" + this.language;
}
}
console.log(myFavoriteDocumentary.name);
console.log(myFavoriteDocumentary.getFavFilm());
var dir = myFavoriteDocumentary.director;
function dirFake(dir) {
console.log("The directors are: " + dir);
dir = "Vertov";
console.log( dir + " is not the director" );
}
dirFake(dir);
console.log( dir + " are the true directors!" );
sorry for the formatting the log shows following result:
Chronicle of a Summer. VM178:11
My favorite non-fiction film is:
Chronicle of a Summer.
Directed by:
Jean Rouch and Edgar Morin.
Year of film:
1961.
Language:
French. VM178:12
The directors are: Jean Rouch and Edgar Morin. VM178:17
Vertov is not the director VM178:19
Jean Rouch and Edgar Morin. are the true directors!
Hope that answers your question.
I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";
i'm able to parse in and display data for all pieces of my code except in this line
" where: " + e.gd$where.valueString + // < this line is displaying undefined
here is the code block that is doing the processing. everything else displays correct data
Titanium.API.info(cal.feed.entry.length);
var i;
for (i=0; i < cal.feed.entry.length; i++){
var e = cal.feed.entry[i];
Titanium.API.info("title: " + e.title.$t +
" content " + e.content.$t +
" when: " + e.gd$when[0].startTime + " - " + e.gd$when[0].endTime +
" evenstatus" + e.gd$eventStatus.value +
" where: " + e.gd$where.valueString + // < this line is displaying undefined
" gcal$uid: " + e.gCal$uid.value
);
here is what should be displayed from the calendar
"gd$where": [{
"valueString": "Any of the 11 elementary schools"
}],
gd$where is an array of objects. In order to access "valueString" in the first key, you need to access it from within that object, like so:
gd$where[0].valueString