duk_enum() 的基本用法是:
/* Assume target object to enumerate is at obj_idx.
* For a function's 1st argument that would be 0.
*/
duk_enum(ctx, 0 /*enum_flags*/); /* Pushes enumerator object. */
while (duk_next(ctx, -1, 1 /*get_value*/)) { /* -1 points to enumerator, here top of stack */
/* Each time duk_enum() finds a new key/value pair, it
* gets pushed to the value stack. So here the stack
* top is [ ... enum key value ]. Enum is at index -3,
* key at -2, value at -1, all relative to stack top.
*/
printf("enumerated key '%s', value '%s'\n", duk_safe_to_string(ctx, -2), duk_safe_to_string(ctx, -1));
/* When you're done with the key/value, pop them off. */
duk_pop_2(ctx);
}
duk_pop(ctx); /* Pop enumerator object. */
如果您不希望自动推送值,请将 0 传递给 duk_next() 的“get_value”参数,并在循环结束时仅弹出键。
duk_enum() 有一组标志来控制您要枚举的内容。0 对应于“for (var k in obj) { ... }”枚举。