简体   繁体   English

JS 对象的数组值和键中的引号不一致

[英]Inconsistent quotes in the JS object's array values and keys

const roads = ["Alice's House-Bob's House", "Alice's House-Cabin", "Alice's House-Post Office"]; 

function buildGraph(edges) {
    let graph = Object.create(null);
    function addEdge(from, to) {
        if (graph[from] == null) {
            graph[from] = [];
        }
        graph[from].push(to);    
    }
    for (let [from, to] of edges.map(r => r.split("-"))) {
        addEdge(from, to);
        addEdge(to, from);
    }
    return graph;
}

const roadGraph = buildGraph(roads);
console.log(roadGraph);

//roadGraph object:
[Object: null prototype] {
"Alice's House": [ "Bob's House", 'Cabin', 'Post Office' ],
"Bob's House": [ "Alice's House" ],
Cabin: [ "Alice's House" ],
'Post Office': [ "Alice's House" ]
}

Why do we have such inconsistencies?为什么我们会有这样的不一致?

  • Cabin and Post Office values in Alice's House are in single quotes Alice's House 中的 Cabin 和 Post Office 值用单引号括起来
  • the Cabin key has no quotes Cabin key 没有引号
  • Post Office key has single quotes邮局键有单引号

In JavaScript, single and double quotes are interchangeable.在 JavaScript 中,单引号和双引号是可以互换的。 You can use whichever you prefer.您可以使用您喜欢的任何一种。

Double quotes are often preferred when the string contains single quotes, as it reduces the amount of escaping:当字符串包含单引号时,通常首选双引号,因为它减少了转义量:

"Alice's House"
'Alice\'s House'

It would appear that the console prefers single quotes, but switches to double quotes when the string contains an apostrophe (single quote).看起来控制台更喜欢单引号,但当字符串包含撇号(单引号)时会切换到双引号。

In general, some prefer to choose a single style and stick to it, but there is no requirement to do so, so it's up to the developer or team.一般来说,有些人更喜欢选择一种风格并坚持下去,但没有强制要求,所以这取决于开发人员或团队。 However, for auto-generated code, there is no need to be concerned.但是,对于自动生成的代码,则无需担心。

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

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