[英]Updating elements of a multidimensional array
I'm seeking to update a team results array below. 我正在尝试更新以下团队结果数组。 The football score will populate positions 1 and 2 of each inner array.
足球比分将填充每个内部阵列的位置1和2。
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: 使用“拼接”可更新固定装置1中A队的得分:
teamResults[1].splice(1,1,3);
["A" ,3 ,undefined ,"B"]
However, using the same method for team B fails. 但是,对团队B使用相同的方法会失败。 It overwrites Teams A's score and the element for Team B's score disappears completely?
它会覆盖A队的得分,而B队的得分元素会完全消失吗?
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: Array.prototype.splice()语法为:
var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
var arrDeletedItems = array.splice(start [,deleteCount [,item1 [,item2 [,...]]]])
So teamResults[1].splice(1,2,4);
所以
teamResults[1].splice(1,2,4);
will remove 2 element from index 1 and then add 4. 将从索引1中删除2个元素,然后加4。
In your case it should be teamResults[1].splice(2,1,4);
在您的情况下,应为
teamResults[1].splice(2,1,4);
var arr = ["A" ,3 ,undefined ,"B"]; arr.splice(2, 1, 4); console.log(arr)
为什么不通过索引分配值而不进行拼接。
teamResults[1][1] = 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.