简体   繁体   English

javascript中未定义的键/值对

[英]key-value pair undefined in javascript

For some reason I have a string like this: 由于某种原因,我有一个像这样的字符串:

"id: 123, title: something, category: science, ... "

To make a javascript object containing the key-value pairs I wrote the following method: 为了制作一个包含键值对的javascript对象,我编写了以下方法:

function stringToMap(stringToCut){
    var map = {};
    var listOfPairs = stringToCut.split(",");
    for(var i = 0; i < listOfPairs.length; i++){
        var pair = listOfPairs[i].split(":");
        map[pair[0]] = pair[1];
    }

    return map;

} }

it's important to access it with dot, not with [] brackets. 请务必使用圆点而不是[]括号来访问它。 In chrome debug mode I see the expected object, but when I want to access one of it's element, like: 在chrome调试模式下,我看到了预期的对象,但是当我想访问它的元素之一时,例如:

console.log(obj.title);

I get undefined... 我不确定...

What Am I doing wrong? 我究竟做错了什么?

It's because there's a space in your key name: 这是因为您的键名中有一个空格:

console.log(obj[" title"]); // "something"

To fix this, change your first split to split on ", " instead of just "," : 为了解决这个问题,改变你先拆拆就", "而不是仅仅","

var listOfPairs = stringToCut.split(", ");

JSFiddle demo . JSFiddle演示

As a further fix, you'll also want to change your second split to split on ": " rather than just ":" , otherwise all your values will begin with spaces. 作为进一步的修正,你还需要改变你的第二分割拆就": "而不仅仅是":" ,否则所有的值将会以空格开头。

var pair = listOfPairs[i].split(": ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM