微信小程序js代码问题
我在编写js代码利用条件运算符(==)来判断两个数值时,为何会出现变量的绑定。
如:if(body[0].x == point.x){
//做一些事情
}为什么会出现改变point.x的值时,body[0].x的值出跟着改变???
以下是部分源代码:
//变量声明 data: { //direction取值: //1:右 2:左 //3:上 4:下 body: [ { x: 30, y: 10, color: '#00ff00' ,}, { x: 20, y: 10, color: '#0000ff' }, { x: 10, y: 10, color: '#ff0000' } ], food_point: { x: 50, y: 50, color: '#f0f00f' }, direction: 1, stop_flag: 0, timer: null , food_color: [ '#ff0000' , '#ff7f00' , '#ffff00' , '#00ff00' , '#00ffff' , '#0000ff' , '#8b00ff' , '#800000' , '#ff00ff' ], eat_flag: 0 }, //条件判断,执行动作 //如果吃到食物 if (( this .data.body[0].x == this .data.food_point.x) && ( this .data.body[0].y == this .data.food_point.y)){ //将食物添加到蛇的头部 var temp_x = this .data.food_point.x; this .data.food_point.x = temp_x + 10; var len = this .data.body.unshift( this .data.food_point); //向蛇数组头部添加数据 this .setData({eat_flag: 0}); } next.x = this .data.body[0].x + 10; next.y = this .data.body[0].y; for (i = 0;i < this .data.body.length;i++){ temp.x = this .data.body[i].x; temp.y = this .data.body[i].y; this .data.body[i].x = next.x; this .data.body[i].y = next.y; next.x = temp.x; next.y = temp.y; } //改变食物位置 if ( this .data.eat_flag == 0){ this .data.food_point.x = parseInt(Math.random() * 36)*10; this .data.food_point.y = parseInt(Math.random() * 24)*10; this .data.food_point.color = this .data.food_color[parseInt(Math.random() * this .data.food_color.length)]; this .setData({eat_flag: 1}); } |
经过测试发现,如果把unshitf()函数去掉,就不会出现问题。但是这里需要用到unshift函数向数组的开头添加数据。