简体   繁体   中英

Splice JavaScript array

Here's my attempt at trying to remove a value from an array dynamically

$('.btn-remove').click(function() {
    var players = ["compare","13076","13075","13077","12755"];
    var removePlayer = $(this).data('player');
    var idx = $.inArray(removePlayer, players);
    if (idx != -1) {
        players.splice(idx, 1);
    }
    window.location = "/" + players.join('/');
})

For example, $(this).data('player') could equal 13077 and i'd want it to remove that value from the array and then redirect to the url which is attached to the window.location variable

The issue here is that .data converts the player data string value to a number:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation... The string value "100" is converted to the number 100.

In your example, you're doing

$.inArray(13077, ["compare","13076","13075","13077","12755"]);

rather than

$.inArray("13077", ["compare","13076","13075","13077","12755"]);

You must either convert the data value back to a string (eg, removePlayer += "" ) or fill the array with number values instead of strings.

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