Javascript 中几种数组赋值的区别及=号的作用

Wayne posted @ Fri, 18 Nov 2016 15:17:26 +0000 in Experience with tags Javascript , 1919 readers

Javascript中,目前要把一个数组的内容等于另一个数组,我会的手段大致有三种:

  1. a = b;

  2. a = b.slice(0);

  3. b.forEach(function(element){ a.push(element);});

这三种有什么不同呢?

 

这三种写法的不同究其原因都出在=号的作用上。数组间的等号可以认为是一个别名。也就是 a = b 的效果等同于 b.alias => a, 给 b 取了个叫a的别名。数组还是同一个数组,多了个名字而已。于是不论用名字 a 操作还是用名字 b 操作,改变的都是同一个数组,换个名字都能看到效果。比如:

var b = [1];
var a = b;
a.push(2);
b.push(3);
console.log(a);  //[1,2,3]
console.log(b);  //[1,2,3]

而 b.slice(0) != b 本身, 只是等于 b 的内容。 a = b.slice(0); 相当于先 new 了一个新的匿名 array,内容为 b 的内容,然后取了个名字叫 a。因为是new出来的,所以用 a = b.slice(0) 后,操作 a  和操作 b 是操作两个不同的数组。

 

那么,什么时候用第三种呢?要用第三种,很明显,首先 a 必须是一个已经存在的数组,不然会报 undefined。第三种的使用场景有比如这样的:

var a = [];
var b = [1];
var c;
afunction(a){ c = a;};  //一个函数,使用a作为传入参数,只调用一次

//此时想把 b 的值赋给c。

因为 c 只在函数体内才能被赋值,而这个值只能通过a来进行。 如果用 a = b, 那么效果等同于 (Original Array a) . removeName(a), 然后 b.alias(a);  而 c 依然是那个 Original Array a,只是丢失了原本a这个名字,只剩下c这个名字了。类似的,如果用 a = b.slice(0), 也无法改变c,只是让c这个数组丢失了另一个叫a的名字而已。这时候,用第三种,把 b 的内容逐个加到已有的 a 里面,才能同时操作到 c。

 

incometaxindiaefilin said:
Sun, 31 Jul 2022 06:02:40 +0000

The Income Tax department of India is a centralized form of association where they keep track of tax redemption from people all across India, and we have seen people surrounding us talk about Income tax refund and the status of the application most of the times. incometaxindiaefiling As you already know that the department makes a small deduction from your salaried account and sometime during December you are eligible to apply for tax refund application. Once you have applied for the refund process then the Income Tax department takes around 3-4 months and releases the status of every application basing on their calculation, but in order for all the steps to happen that we've mentioned it is necessary for you to apply for the tax refund in the first place.

AP 6th Class Telugu said:
Wed, 21 Sep 2022 17:20:37 +0000

Telugu is the first or mother language for all Telugu Medium students studying at the state board of Andhra Pradesh. Those Class 6th Standard students studying other medium schools have chosen Telugu as a Second or Third language from their electives. AP 6th Class Telugu Question Paper Every government and private school on the state board is working with SCERT Syllabus & curriculum. Telugu is the first or mother language for all Telugu Medium students studying at the state board of Andhra Pradesh. Those Class 6th Standard students studying other medium schools have chosen Telugu as a Second or Third language from their electives.


Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter