You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matrix类中y * width + x表达式及赋值语句作用解析

解析Matrix类中y * width + x表达式及对应语句的作用

一、y * width + x的作用

这个表达式的核心是把二维矩阵的坐标(x,y)转换成一维数组的索引。JavaScript没有原生的二维数组,这里用一维数组content模拟二维矩阵,这种方式比嵌套数组更节省内存、访问速度更快。

拿示例里的2×2矩阵举例:

  • 当y=0(第一行),x取0、1时,索引分别是0*2+0=0、0*2+1=1,对应一维数组的第0、1位
  • 当y=1(第二行),x取0、1时,索引分别是1*2+0=2、1*2+1=3,对应一维数组的第2、3位
    相当于把二维矩阵的每一行元素按顺序平铺进一维数组,行与行完全连续,没有嵌套结构。

二、this.content[y * width + x] = element(x, y)的作用

这条语句负责将二维坐标(x,y)对应的元素值,存入一维数组的对应索引位置:

  1. 通过y * width + x计算出当前二维坐标在一维数组中的定位
  2. 调用传入的element函数,传入(x,y)坐标生成对应的值(比如示例里的value x,y)
  3. 把生成的值赋值给content数组的对应索引,完成二维矩阵元素的初始化

完整代码示例

class Matrix { 
    constructor(width, height, element = (x, y) => undefined) { 
        this.width = width; 
        this.height = height; 
        this.content = [];

        for (let y = 0; y < height; y++) { 
            for (let x = 0; x < width; x++) {
                this.content[y * width + x] = element(x, y); 
                console.log(this.content[y * width + x] = element(x, y));
            } 
        } 
    } 

    get(x, y) { 
        return this.content[y * this.width + x]; 
    } 
    set(x, y, value) { 
        this.content[y * this.width + x] = value; 
    } 
} 

class MatrixIterator { 
    constructor(matrix) { 
        this.x = 0; 
        this.y = 0; 
        this.matrix = matrix; 
    } 
    next() { 
        if (this.y == this.matrix.height) return {done: true}; 
        let value = {x: this.x, y: this.y, value: this.matrix.get(this.x, this.y)};

        this.x++; 
        if (this.x == this.matrix.width) { 
            this.x = 0; 
            this.y++; 
        } 
        return {value, done: false}; 
    } 
}

Matrix.prototype[Symbol.iterator] = function() { 
    return new MatrixIterator(this); 
};
    
// 现在可以用for/of遍历矩阵了
let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
console.log(matrix);
for (let {x, y, value} of matrix) { 
    console.log(x, y, value);
}

// 输出结果:
// → 0 0 value 0,0 
// → 1 0 value 1,0 
// → 0 1 value 0,1 
// → 1 1 value 1,1

内容的提问来源于stack exchange,提问作者Jesse J Sosmena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 03:18:41