JavaScript.字典键不是字符串?



只是一个简单的问题。有下一段代码:

function addMarker(data) {
var types = {'meet': 380 + ',' + 95, 'vegetable': 285 + ',' + 0};
var selection = data.type;
console.log(types["meet"]);
console.log(types[selection]);
console.log(selection);

并在控制台中显示以下结果:

380,95
undefined
Meet

在第二种情况下,我还需要 380,95。selection应该是来自data对象的字符串。不知何故,当像字典键一样使用此字符串时,它不起作用。那么我该怎么能以这样的动态方式从types中获取不同的值呢?

澄清一下,我不是想获得浮点数,我需要的是两个用,分隔的数字

Javascript 区分大小写。对象具有属性meet选择的值为Meet。因此,您需要将代码更新为以下内容

console.log(types[selection.toLowerCase()]);

作为参考,String.toLowerCase((

请检查是否

data.type === "Meet" // true

它应该是"满足"。

顺便说一句,它是拼写肉,而不是见面。

只是为了清楚

addMarker({'type':'meet'}) // would produce correct result 
addMarker({'type':'Meet'}) // would produce result  result you see 

要更正此问题,您可以使用小写字符串,如 Nikhil 提供

的那样
function addMarker(data) {
var types = {'meet': 380 + ',' + 95, 'vegetable': 285 + ',' + 0};
var selection = data.type;
selection = selection.toLowerCase();
console.log(types["meet"]);
console.log(types[selection]);
console.log(selection);
}

或者只是打正确的电话

最新更新