Node.js C++ 插件 - 设置数组的特定索引

Node.js C++ Addon - Setting a certain index of an array

我正在尝试创建一个 Node.js C++ 插件来生成斐波那契数列以将其速度与普通 Node.js 模块进行比较,但我无法设置某个索引大批。到目前为止我已经知道了:

#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Value;
using v8::Number;
using v8::Array;

void Method(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    int next, first = 0, second = 0, c = 0, n = args[0]->NumberValue();
    Local<Array> arr = Array::New(isolate, n);

    for (; c < n; c++) {
        if ( c <= 1 ) next = c;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        // How to set arr[c]?????
    }

    args.GetReturnValue().Set(arr);
}

void init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "fib", Method);
}

NODE_MODULE(addon, init)

}

第26行,arr[c]怎么设置? v8:Array 不提供下标运算符。

how should I set arr[c]? v8:Array doesn't provide a subscript operator.

它没有,但是 v8::Array 已经从 v8::Object 继承了函数成员 Set,并且重载采用整数 (uint32_t) 作为键.用它来填充数组的每个元素:

void Method(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    int next, first = 0, second = 0, c = 0, n = args[0]->NumberValue();
    Local<Array> arr = Array::New(isolate, n);

    int i = 0;
    for (; c < n; c++) {
        if ( c <= 1 ) next = c;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        arr->Set(i++, Number::New(isolate, next));
    }

    args.GetReturnValue().Set(arr);
}