简体   繁体   中英

JavaScript splice and place into another array

I'm currently making a game which requires me to take an object from an array and place it into another array.

a = obj;
array1.splice(a);
array2.push(a);

(a is already in array1)

This is pretty much what I need to happen.

I'm not an expert so please explain your answer in depth.

Javascript Array Splice() Method works as following...

array.splice(index,howmany)

It takes index number of the item to remove, how many items to remove as it's parameter and these two are required.

For more you can follow this link : http://www.w3schools.com/jsref/jsref_splice.asp

So, your problem can be solved as following...

a = obj;
var index = array1.indexOf(a);
array1.splice(index,1);
array2.push(a);

splice(start, ?deleteCount) The function is used to get one or more elements in an array and remove the selected elements from the array.

slice(?start, ?end) slice retreive selected elements without change array.

for example i have this array :

const months = ['Jan', 'March', 'April', 'June'];

let selectedElementsWithSlice = months.slice(2, 3);
//["April"]
// months = ['Jan', 'March', 'April', 'June']

let selectedElements = months.splice(2, 1); // removed from array months
//["April"]
// months = ['Jan', 'March', 'June']

For your subject you want copy element to other array.

You have a multiples solutions :

  1. for first element selected (check if contains if necessary)
array.push(months.slice(2, 3)[0]);
  1. For all elements selected
[ ... array, ... months.slice(2, 3) ]

References :

splice documentation : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

slice documentation : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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