我有一个数组对象和一个数组,如下所示:
let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
let selected = [];
我实现了点击进入
data
数据
selected
. 在其ID为的索引中,没有
挑选出来的
1
const dataObject = {"name": "Apple"};
dataObject['position'] = selected.length;
selected.push(dataObject);
-
const dataObject = {"name": "Apple"};
selected.push(dataObject);
for(let i = 0; i<selected.length; i++) {
selected[i]['position'] = i;
}
奇怪的是如果有相同的物体
Apple, Orange, Apple
,我在数组中得到了错误的ID,比如:
[{"name": "Apple", position: 2} , {"name": "Orange", position: 1}, {"name": "Apple", position: 2}]
#编辑:
这里是可复制代码:
let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
let selected = [];
const dataObject = {"name": "Apple"};
selected.push(dataObject);
selected.push(dataObject);
for(let i = 0; i<selected.length; i++) {
selected[i]['position'] = i;
}
document.write('<br>' + JSON.stringify(selected));
// Output : [{"name":"Apple","position":1},{"name":"Apple","position":1}]
// Output Expect: [{"name":"Apple","position":0},{"name":"Apple","position":1}]
我不知道是什么错,任何建议都会对我有帮助。提前感谢