我有以下代码:

let toDayKey    = toDayKey.toString(); // 1
const deptId    = deptId.toString();  // 3
const jobId     = jobId.toString();  // 87

//Assuming copied.toJS() is any value like "copied job"

const calendar_job_add      = calendar_job_removed.setIn([toDayKey,deptId,jobId], copied_job.toJS());


calendar_job *是一个不可变的映射,我正在尝试使用jobId作为键将87添加一个值

而不是得到

calendar_job_add = {"1": { "3": {"87": "the copied job" } } }


我得到这个代替:

calendar_job_add = {"1": { "3": {
0: undefined,
1: undefined,
2: undefined,
3: undefined
...
..
.
87: "copied job"
} } }


似乎正在将其变成Array对象而不是Object并插入未定义的值。是什么赋予了?

任何建议深表感谢。

最佳答案

很难说出代码出了什么问题。当我在setIn上调用Map并将数字键传递给它时,它会一直向下创建嵌套的Map,无论我是对这些键还是使用number'1','2' >等



const before = Immutable.Map({})
console.log('before:', before);

const withStringKeys = before.setIn(['1', '2', '3'], 'a')
console.log('with string keys:', withStringKeys);

const withNumberKeys = before.setIn([1, 2, 3], 'b')
console.log('with number keys:', withStringKeys);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>





我发现遇到问题的唯一方法是尝试'3'已经是setIn的东西。例如:



const before = Immutable.fromJS({ 1: { 2: [] } });
console.log('before:', before);

const withStringKeys = before.setIn(['1', '2', '3'], 'a')
console.log('with string keys:', withStringKeys);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>

关于javascript - 如何使setIn在immutable.js中设置数字键而不是数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49102272/

10-11 23:59