如何从javascript中矩阵的每一行中删除最后一个元素 [英] How to remove last element from every row of a matrix in javascript
问题描述
我正在尝试从javascript矩阵的每一行中删除最后一个元素.我正在尝试使用地图"功能,但未成功.
I am trying to remove the last element from every row of a matrix in javascript. I am trying to use the "map" function but I am not successful.
这是我的代码:
var matrixWithExtraInfo = [
[1, 2, 3, 4, "dog"],
[5, 6, 7, 8, "dog"],
[9, 10, 11, 12, "dog"],
[13, 14, 15, 16, "dog"],
[17, 18, 19, 20, "dog"]
];
var conciseMatrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]
]
var conciseMatrix = matrixWithExtraInfo.map(function(index) {
console.log(index)
matrixWithExtraInfo[index].pop();
return matrixWithExtraInfo[index];
});
console.log(matrixWithExtraInfo);
我知道
TypeError:无法读取未定义的属性"pop"
TypeError: Cannot read property 'pop' of undefined
推荐答案
.map
的第一个参数是您要遍历的项目,而不是索引.
The first argument to .map
is the item you're iterating over, not the index.
由于这里的每个项目都是一个数组,因此您可以 .pop
数组(将对现有数组进行 muting 更改)或 .slice
数组(不会改变现有数组).
Since each item here is an array, you can either .pop
the array (which will mutate the existing array), or .slice
the array (which will not mutate the existing array).
var matrixWithExtraInfo = [
[1,2,3,4,"dog"],
[5,6,7,8,"dog"],
[9,10,11,12,"dog"],
[13,14,15,16,"dog"],
[17,18,19,20,"dog"]
];
var conciseMatrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16],
[17,18,19,20]
]
var conciseMatrix = matrixWithExtraInfo.map((arr) => {
arr.pop();
return arr;
});
console.log(matrixWithExtraInfo);
console.log(conciseMatrix);
(上面是 weird -您需要的结构已经在 matrixWithExtraInfo
中,使保存它的另一个变量令人困惑,但这与您的原始代码最接近)
(the above is weird - the structure you need is already in matrixWithExtraInfo
, making another variable to hold it is confusing, but this is the closest to your original code)
var matrixWithExtraInfo = [
[1,2,3,4,"dog"],
[5,6,7,8,"dog"],
[9,10,11,12,"dog"],
[13,14,15,16,"dog"],
[17,18,19,20,"dog"]
];
var conciseMatrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16],
[17,18,19,20]
]
var conciseMatrix = matrixWithExtraInfo.map(arr => arr.slice(0, -1));
console.log(matrixWithExtraInfo);
console.log(conciseMatrix);
这篇关于如何从javascript中矩阵的每一行中删除最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!