简体   繁体   English

Python 的字典 get 方法的 Javascript 等价物是什么

[英]What is the Javascript equivalent of Python's get method for dictionaries

Python's get method for dictionaries lets me specify what should be returned if a key doesn't exist. Python 的字典 get 方法让我指定如果键不存在应该返回什么。 For my current case I want a dictionary returned.对于我目前的情况,我希望返回一本字典。 How do I do this in Javascript?我如何在 Javascript 中做到这一点?

There is no javascript equivalent of the python dictionary get method.没有与 python 字典 get 方法等效的 javascript。 If you would write it yourself, as a function, it would look like this:如果你自己写,作为一个函数,它看起来像这样:

function get(object, key, default_value) {
    var result = object[key];
    return (typeof result !== "undefined") ? result : default_value;
}

Use it like:像这样使用它:

var obj = {"a": 1};
get(obj, "a", 2); // -> 1
get(obj, "b", 2); // -> 2

Note that the requested key will also be found in a prototype of obj.请注意,请求的密钥也将在 obj 的原型中找到。

If you really want a method rather than a function ( obj.get("a", 2) ), you need to extend the prototype of Object.如果你真的想要一个方法而不是一个函数( obj.get("a", 2) ),你需要扩展 Object 的原型。 This is generally considered a bad idea though, see Extending Object.prototype JavaScript不过,这通常被认为是一个坏主意,请参阅扩展 Object.prototype JavaScript

JavaScript has no helper feature to do that. JavaScript 没有帮助功能来做到这一点。 You need to test explicitly.您需要明确地进行测试。

if ("myProperty" in myObject) {
    return { another: "object" };
} else {
    return myObject.myProperty;
}

You can use a ternary operator to do the same thing with less code.您可以使用三元运算符以更少的代码执行相同的操作。

return ("myProperty" in myObject) ? myObject.myProperty : { another: "object" };

You could use a proxy for this (really new ):您可以为此使用代理(非常新):

var handler = {
    get: function(target, name){
        return name in target?
        target[name] :
        "Default";
    }
};
var dictionary={"hi":true};
var dict = new Proxy(dictionary, handler);
dict.a = 1;
dict.b = undefined;

console.log(dict.a, dict.b,dict.hi); // 1, undefined,true
console.log(dict.new); //"Default"

 //the proxied object gets changed:

console.log(dictionary.a, dictionary.b,dictionary.hi); // 1, undefined,true
console.log(dictionary.new); //undefined

A proxy is an object that reflects all changes and requests trough an handler.代理是通过处理程序反映所有更改和请求的对象。 In this case we can write/access propertys of dictionary normally, but if we access values that do not exist it'll return "Default"在这种情况下,我们可以正常写入/访问字典的属性,但是如果我们访问不存在的值,它将返回“默认”

I prefer to use the logical OR like this:我更喜欢像这样使用逻辑 OR:

foo.bar || 'default'

If checks is foo.bar is falsy, so it returns 'default' if bar is undefined.如果检查是 foo.bar 是假的,所以如果 bar 未定义,它返回 'default'。

You just need to care, that foo is an object.你只需要关心, foo 是一个对象。 Otherwise a ReferenceError is thrown.否则会抛出一个 ReferenceError。

this works for me这对我有用

let obj = {"a": 1};
let default = 100
obj["a"] || default; // -> 1
obj["b"] || default; // -> 100

But!但是! there are some limitation, if !!obj["a"] === false we always get default value... so it's better to just check if key in obj, to be completely sure.有一些限制,如果!!obj["a"] === false我们总是得到默认值......所以最好只检查 obj 中的键,以完全确定。

With modern javascript you can use the ??使用现代 javascript,您可以使用?? operator 操作员

const result = obj[key] ?? default;

Note that cases like {myKey: undefined} or {myKey: null} will also return the default value, which may or may not be the desired behaviour.请注意,像{myKey: undefined}{myKey: null}这样的情况也将返回默认值,这可能是也可能不是所需的行为。

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

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