简体   繁体   English

与另一个数组相等的数组并拼接

[英]Equal Array to Another Array And Splice

I have two array.我有两个数组。 I want to delete these elements of array after equal according to other array length.我想根据其他数组长度在相等后删除这些数组元素。 it removes elements.它删除元素。 but it removes all elements of both arrays.但它删除了 arrays 的所有元素。 why is it remove all elements of both arrays?为什么要删除 arrays 的所有元素?

var fruits = ["Banana", "Orange", "Apple", "Mango"];
let sefa = [];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {

sefa = fruits;
fruits.push("element-1");
fruits.push("element-2");

  fruits.splice(0, sefa.length);
  document.getElementById("demo").innerHTML = fruits;
}

console.log(fruits) => Array[] console.log(fruits) => 数组[]

It removes all the elements of both the arrays because when you do sefa=fruits.它删除了 arrays 的所有元素,因为当您执行 sefa=fruits 时。 It gives the address of fruits array to the array sefa.它将水果数组的地址提供给数组 sefa。

I think instead you should do我认为你应该这样做

sefa = fruits.slice(0,fruits.length);

By this if you remove all the elements of fruits till the length of sefa.通过这个,如果你删除水果的所有元素直到 sefa 的长度。 The sefa array still remains untouched, because the slice function makes a copy of fruits array and gives it to sefa instead of giving the address. sefa 数组仍然保持不变,因为切片 function 复制了 fruits 数组并将其提供给 sefa 而不是提供地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM