给出这个使用lodash的例子:
var object = {};
_.set(object, [ 1, 2 ], 5);
console.log(object);
Run Code Online (Sandbox Code Playgroud)
控制台中的结果对象是:
{
1: [undefined, undefined, 5]
}
Run Code Online (Sandbox Code Playgroud)
现在想象一下,而不是整数2,你设置的时间戳为1445231475.你现在在一个非常大的数组中有1445231474个未定义的值,在一些_.set
操作后将耗尽内存.
如果可能的话_.set
,如何创建这个对象:
{
1: {
2: 5
}
}
Run Code Online (Sandbox Code Playgroud)
如果2真的是一个像"a"这样的字符串,那么Lodash可能会强制"2"进入多个未定义值的数组.
我可以_.merge
在必要时使用,但我会更兴奋使用_.set
功能.
你可以用lodash做到这一点 setWith
// unwanted behavior with set
let x = {}
_.set(x, [1,2], 'test')
// x = { '1': [ <2 empty items>, 'test' ] }
// desired behavior with setWith
let y = {}
_.setWith(y, [1,2], 'test', Object)
// y = { '1': { '2': 'test' } }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3389 次 |
最近记录: |