json格式对象大括号中不能把键改为变量问题
发布日期:2022-02-22 18:04:18 浏览次数:11 分类:技术文章

本文共 1006 字,大约阅读时间需要 3 分钟。

今天遇到了一个往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

转载地址:https://blog.csdn.net/dianshanban9429/article/details/101311479 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:AWS ALB使用cognito认证时遇到redirect_mismatch错误
下一篇:MySQL聚合函数在计算时,不会自动匹配与之相对应的数据

发表评论

最新留言

不错!
[***.144.177.141]2024年04月05日 18时04分44秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章