简体   繁体   中英

Delete an array element in Set in Javascript

Take the following example:

var s = new Set([1,2,3]);
s.add([4,5]); //Set(5) {1, 2, 3, 4, [4, 5]}
s.delete([4,5]);//false

I also tried s.delete(Array(4,5)) and s.delete('[4,5]') , but they don't work either.

Why is that? Do I have to consider the implementation code of the delete function?

The [4,5] you add is a different object than the [4,5] you tell it to delete. Remember, objects are referenced in JS, so you're using two separate references to two different objects that just happens to look the same.

Here's how you use the same object and its reference:

var s = new Set([1,2,3]);
var newItem = [4, 5];
s.add(newItem); //Set(5) {1, 2, 3, 4, [4, 5]}
s.delete(newItem);

It's not the implementation of the delete method you need to consider, as it's completely consistent regardless of what you pass it, you need to consider the fact that in JS object types are always referenced while primitive types are not.

You need a reference to the array for deleting the same array. Objects are different if they do not share the same reference.

 var s = new Set([1, 2, 3]), a = [4, 5]; s.add(a); console.log([...s]); s.delete(a); console.log([...s]);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

This is because you need to pass a reference to the array you want to remove to delete , rather than a separate array that happens to have the same values.

Try this:

var s = new Set([1,2,3]);
var array = [4,5];

s.add(array);

console.log('before: ' + [...s]);

s.delete(array);

console.log('after delete: ' + [...s]);

JSBin: http://jsbin.com/nedoxenevu/1/edit?html,js,console

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