我正在开发一个需要从JS输入日期的应用程序,并在JSON表中检查当天的“字母”是什么。
如何获取我创建的JS日期字符串(yyyy,mm,dd),并找到相应键的值?
我尝试过将字符串字符串化,字符串化,然后通过JS函数推送它。
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var dateStr = year + "/" + month + "/" + date;
console.log(dateStr);
dateJSON = JSON.stringify(dateStr)
console.log(dateJSON)
alert(testVar.dateJSON)
var testVar = { //In a JS file
"2019-11-06": "D",
"2019-11-08": "A_con" //continues for a very long time.....
}
对于“ 2019-11-08”,我希望变量“ letterDay”等于“ A_con”。
到目前为止,当我提取“ testVar.dateJSON”时,我的代码返回“未定义”
最佳答案
我认为这要简单得多,您的数据密钥采用yyyy-mm-dd
格式,而您dateStr
则采用yyyy/mm/dd
格式,这是一个简单的代码段
var testVar = { //In a JS file
"2019-11-09": "D",
"2019-11-08": "A_con" //continues for a very long time.....
}
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
// Your mistake was here, the separators were '/'
var dateStr = year + "-" + month + "-" + date;
console.log(dateStr);
// Get the value dynamically
// when you have a dynamic key use testVar[dateStr]
// testVar.dateStr will literally look for a key called "dateStr" it will not evaluate the value of dateStr
console.log(testVar[dateStr]);
关于javascript - 如何从JSON到JS获取键的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58772717/