【问题标题】:Pushing x and y values into array variables将 x 和 y 值推入数组变量
【发布时间】:2020-02-13 11:56:44
【问题描述】:

我有一个包含变量的数组。我想将一些 x 和 y 坐标推送到数组中,但是当我尝试推送而不是更改变量值时,推送会创建新变量并将值分配给这些变量。

原来是这样的

0: {id: "t523470", name: "tPm1", x: 0, y: 0, parent: null, …}
1: {id: "t523471", name: "tPm2", x: 0, y: 0, parent: null, …}
2: {y: 651, x: 446}
3: {y: 800.015625, x: 802.328125}

不是这个

0: {id: "t523470", name: "tPm1", x: 446, y: 651, parent: null, …}
1: {id: "t523471", name: "tPm2", x: 802.328125, y: 800.015625, parent: null, …}




    function getModulePosition(id) {

        for (let i = 0; i < axisViewElements.modules.length; i++) {



            let currentElement = axisViewElements.modules[i].id;
            if (id === currentElement) {
                continue;
            }
            let module = document.getElementById(currentElement);

            let modulePos = { x: module.getBoundingClientRect().left, y: module.getBoundingClientRect().top }
            console.log(modulePos);



            axisViewElements.modules.push({

                y: modulePos.y,
                x: modulePos.x

            });


        }
    }

【问题讨论】:

    标签: javascript arrays sorting d3.js svg


    【解决方案1】:

    Array push 方法总是在数组中插入一个新元素。当您需要更新现有元素时,您只需执行以下操作:

    axisViewElements.modules[i].y = modulePos.y;
    axisViewElements.modules[i].x = modulePos.x;
    

    【讨论】:

      【解决方案2】:

      Array.prototype.push 总是用你的值创建一个新索引。您不能使用 .push() 并期望更改数组中的先前值。为了您的目的,您必须遍历数组,找到要更改其中某些值的索引,然后将新值分配给它们。

      【讨论】:

        【解决方案3】:

        您正在推送到总是创建新元素的数组。

        我假设您的元素在数组内部是唯一的,就其id 属性而言。所以你必须找到带有id 的元素,然后更新xy 属性。

        你的代码会是这样的:

        elementToUpdate = axisViewElements.modules.find(el => el.id === you_id)
        elementToUpdate.x = modulePos.x
        elementToUpdate.y = modulePos.y
        

        【讨论】:

          【解决方案4】:

          在这里试试https://runkit.com/embed/pd68veqr5ey7

          let input = [
            {id: "t523470", name: "tPm1", x: 0, y: 0, parent: null},
            {id: "t523471", name: "tPm2", x: 0, y: 0, parent: null}
          ];
          
          let newValue = [
           {y: 651, x: 446},
           {y: 800.015625, x: 802.328125}
          ];
          
          input.forEach((item, index) => item = Object.assign( item , newValue[index]));
          console.log(input);
          

          【讨论】:

            猜你喜欢
            • 2017-04-02
            • 1970-01-01
            • 1970-01-01
            • 2013-06-04
            • 1970-01-01
            • 2016-11-17
            • 1970-01-01
            • 2011-11-29
            • 1970-01-01
            相关资源
            最近更新 更多