【问题标题】:Function to create properties of an object?创建对象属性的函数?
【发布时间】:2019-11-25 21:34:41
【问题描述】:

我是 javascript 新手,正在尝试编写游戏代码。

我需要创建一个存储 10 个“列”高度的对象。这些列必须设置为零。所以我需要这样的东西:

var columnLevel = {c1 : 0, c2 : 0, c3 : 0, c4 : 0 等等...}

但这不切实际,尤其是因为我可能需要在某些时候拥有更多列。

如何创建某种函数来自动将 n 列设置为零?

感谢您的宝贵时间

科伦丁

【问题讨论】:

  • 简单的 for 循环和括号表示法。

标签: javascript function object properties set


【解决方案1】:
for(let i = 0; i < max; i++) {
    columnLevel[`c${i}`] = 0
}

【讨论】:

    【解决方案2】:
    //function that returns a new Object of n columns
    function Columns(colsNum) {
    //empty object
            const newColumns={};
    //adding n consecutive values
            for(let i=0; i<colsNum;i++){
               newColumns["c"+i]=0;
            }
            return newColumns;
        }
    // 5 columns
    const col1= new Columns(5);   
    //25 !!! columns
    const col2= new Columns(25);
    //write to console just to check if as expected
    console.log(col2);
    console.log(col1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2022-06-12
      • 2015-03-24
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      相关资源
      最近更新 更多