json格式对象大括号中不能把键改为变量问题

今天遇到了一个往json中写入变量的问题,下面代码是错误的写法

document.querySelector(".box").onclick = function(){
            // 移动的方向,随机水平或者垂直
            var dir = Math.round(Math.random()) == 1 ? 'top' : 'left';
            // 移动的距离,或正或负
            var range = parseInt(Math.random()*100);
            // 这是一个运动函数,第二个参数为json格式对象
            animate(this,{
                dir:range   // 将变量dir写成键是不生效的
            },function(){
                console.log("完成");
            });
        }

我们发现只有将大括号中的dir改成"left" or "top"才会生效,但是,这样不符合设计初衷,我是想让dir随机变化方向的

所以我找到一种正确的写法,代码如下:

 document.querySelector(".box").onclick = function(){
            // 移动的方向,随机水平或者垂直
            var dir = Math.round(Math.random()) == 1 ? 'top' : 'left';
            // 移动的距离,或正或负
            var range = parseInt(Math.random()*100);
            
            var json = {};
            // 这种写法是对的
            json[dir] = range;
            animate(this,json,function(){
                console.log("完成");
            });
        }
原文地址:https://www.cnblogs.com/Ryan777/p/10528226.html