首页 > Web开发 > 详细

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

时间:2019-03-14 10:22:44      阅读:196      评论:0      收藏:0      [点我收藏+]

今天遇到了一个往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("完成");
            });
        }

 

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

原文:https://www.cnblogs.com/Ryan777/p/10528226.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!