簡體   English   中英

如果將整數初始化為空,則為其提供默認值

[英]Give integers a default value if they are initialized as empty

我有這個(這是一個Node.js插件)

void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {

    int count = args[2]->ToNumber()->NumberValue();
    int priority = args[3]->ToNumber()->NumberValue();
    int priority_search_cap = args[4]->ToNumber()->NumberValue();

    cout << " count => " << count << endl;
    cout << " priority => " << priority << endl;
    cout << " priority_search_cap => " << priority_search_cap << endl;

}

我注銷的是:

 count => -2147483648
 priority => -2147483648
 priority_search_cap => -2147483648

我想做的是為這些變量提供默認值,以防萬一沒有傳遞任何值來正確初始化它們? (意味着,args [2],args [3],args [4]未定義。)

如何給這些整數提供默認值?

Value類型有一個不錯的IsUndefined()方法來檢查

如果值未定義,則可以使用三元表達式將值設置為0:

int count = args[2]->IsUndefined() ? 0 : args[2]->ToNumber()->NumberValue();
int priority = args[3]->IsUndefined() ? 0 : args[3]->ToNumber()->NumberValue();
int priority_search_cap = args[4]->IsUndefined() ? 0 : args[4]->ToNumber()->NumberValue();

在此處檢查Value API: http : //bespin.cz/~ondras/html/classv8_1_1Value.html#aea287b745656baa8a12a2ae1d69744b6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM