I'm seeking to update a team results array below. The football score will populate positions 1 and 2 of each inner array.
var teamResults=[
["Home","F","A","Away"],
["A",,,"B"],
["A",,,"C"],
["B",,,"C"],
["B",,,"A"],
["C",,,"A"],
["C",,,"B"],
];
Initially each score is undefined as below:
console.log(teamResults[1]);
["A" ,undefined ,undefined ,"B"]
Using 'splice' works to update team A's score in fixture #1:
teamResults[1].splice(1,1,3);
["A" ,3 ,undefined ,"B"]
However, using the same method for team B fails. It overwrites Teams A's score and the element for Team B's score disappears completely?
teamResults[1].splice(1,2,4);
["A" ,4 ,"B"]
Any advice on how to produce the following array would be greatly appreciated
["A" ,3 ,4 ,"B"]
The Array.prototype.splice() syntax is:
var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
So teamResults[1].splice(1,2,4);
will remove 2 element from index 1 and then add 4.
In your case it should be teamResults[1].splice(2,1,4);
var arr = ["A" ,3 ,undefined ,"B"]; arr.splice(2, 1, 4); console.log(arr)
为什么不通过索引分配值而不进行拼接。
teamResults[1][1] = 3;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.