在您的
我正在创建一个应用程序,其中用户从客户端输入数据。该数据将存储在localStorage
。在此之前一切正常。但是我需要计算对象的length
,然后在创建和保存每个客户端时自动分配一个连续的数字。由于javascript
对象从0开始编号,例如,array
上的第一个客户端将是0,但在现实生活中它是1。因此,我需要迭代并获得js
订购的最后一个客户端,然后添加1,然后将其分配给clientn
以存储在此客户端数据上。
Json
Clients:"[{
"id":"qece2345-cd9d-4898-fd18-3ded710a8062",
"hasPic":false,
"picId":2,
"picSrc":"",
"picFile":[],
"createdOn":"2023-03-30T14:22:22.899Z",
"firstName":"JND PLUS MASTER",
"job":"Destroza avernos",
"clientn":""
}]"
Js
function setClientNumber() {
var clients = JSON.parse(localStorage.getItem("Clients")) || {};
for (var m = 0; m < clients.length; m++) {
clientNumber = clients.slice(-1)["0"].clientn;
clients.push(client, clientNumber + '1');
localStorage.setItem("Clients", JSON.stringify(clients));
}
预期结果
Clients:"[{
"id":"qece2345-cd9d-4898-fd18-3ded710a8062",
"hasPic":false,
"picId":2,
"picSrc":"",
"picFile":[],
"createdOn":"2023-03-30T14:22:22.899Z",
"firstName":"JND PLUS MASTER",
"job":"Destroza avernos",
"clientn":"1"
},{
"id":"qece2345-cd9d-4898-fd18-3ded710a8062",
"hasPic":false,
"picId":2,
"picSrc":"",
"picFile":[],
"createdOn":"2023-03-30T14:22:22.899Z",
"firstName":"JND PLUS MASTER",
"job":"Destroza avernos",
"clientn":"2"
},{
"id":"qece2345-cd9d-4898-fd18-3ded710a8062",
"hasPic":false,
"picId":2,
"picSrc":"",
"picFile":[],
"createdOn":"2023-03-30T14:22:22.899Z",
"firstName":"JND PLUS MASTER",
"job":"Destroza avernos",
"clientn":"3"
}]"
注意,第一个客户端object 0
有"clientn":1
;object 1
,有"clientn":2
;object 2
,有"clientn":3
.
在您的push
中,由于某种原因,您正在推送两个项目
试试更简单的东西,比如.map
function runSetClientNumber() {
const oldClients = JSON.parse(localStorage.getItem("Clients")) || {};
const newClients = oldClients.map(
(oldClient,zeroBasedIndex)=> ({
...oldClient,
clientn: 1+zeroBasedIndex
})
);
localStorage.setItem("Clients", JSON.stringify(newClients));
}