javascript - 数组索引选择,如 numpy 但在 javascript 中
问题描述
我有一个 3x3 数组:
var my_array = [[0,1,2],
[3,4,5],
[6,7,8]];
并想要获得它的第一个 2x2 块(或任何其他 2x2 块):
[[0,1],
[3,4]]
用 numpy 我会写:
my_array = np.arange(9).reshape((3,3))
my_array[:2, :2]
得到正确的结果。
我在javascript中试过:
my_array.slice(0, 2).slice(0, 2);
但第二个切片影响第一个维度,什么都不做。我注定要使用 for 循环,还是有一些新的 ES6 语法可以让我的生活更简单?
解决方案
可以使用Array.slice
和的组合Array.map
:
const input = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
const result = input.slice(0, 2).map(arr => arr.slice(0, 2));
console.log(result);
推荐阅读
- javascript - 使用 innerHTML 调用 jQuery UI 滑块时不显示
- opencv - 立体相机校准错误
- python-3.x - ortools:如何使用搜索策略sweep和best insert?
- excel - 在数据透视表结果的 IF 内使用 AND 内的 OR
- python - 是否可以使用 setuptools 为 find_packages() 提供多个源目录?
- sql - VBA Sub 似乎正在跳过连接声明
- go - 尝试从多个 go 例程收集数据时出错
- ios - Appcelerator iOS 应用程序:如何从共享扩展中读取钥匙串值?
- python - 从 SQL Python 中提取字节返回字节数组
- python - 参数 1:无法从 'System.Data.SqlClient.SqlDataAdapter' 转换为 'System.Data.DataSet' 并且无法识别列名