与JS变量一件奇怪的事 [英] A strange thing with js variables

查看:116
本文介绍了与JS变量一件奇怪的事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这code警报同样的事情(1,2,3,4)两次??

  VAR ARR = [1,2,3];
VAR new_arr =编曲;
new_arr [new_arr.length] = 4;
警报(new_arr);
警报(ARR);


解决方案

在JavaScript中,所有值要么是原始值(数字,字符串,布尔值,未定义)或对象(阵列,函数,等等)。引用其中

有只有一个阵列和两个变量持有引用此阵列

如果你想有另一个数组,这样就可以独立进行更改,复制第一个:

  VAR ARR = [1,2,3];
变种new_arr = arr.slice();

Why does this code alerts same thing (1,2,3,4) twice??

var arr = [1,2,3];
var new_arr = arr;
new_arr[new_arr.length] = 4;
alert(new_arr);
alert(arr);

解决方案

In JavaScript, all values are either primitive values (numbers, strings, booleans, null, undefined) or references to objects (among them the arrays, functions, etc.).

There is only one array and both variables hold references to this array.

If you want to have another array, so that you can change them independently, duplicate the first one :

var arr = [1,2,3];
var new_arr = arr.slice();

这篇关于与JS变量一件奇怪的事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆