gpt4 book ai didi

javascript - 在javascript中使用拼接从数组中删除所有元素

转载 作者:行者123 更新时间:2023-11-30 07:08:03 24 4
gpt4 key购买 nike

我正在尝试从我的数组中删除一个带有字符串索引的特定元素但是我所有的元素都被删除了

var myArray = new Array();

myArray['abc'] = 'abc';
myArray['cde'] = 'cde';
myArray['efg'] = 'efg';

console.log('before splice:');
console.log(myArray);

myArray = myArray.splice('abc',1);
console.log('after splice:');
console.log(myArray);


before splice:
[abc: "abc", cde: "cde", efg: "efg"]
after splice:
[]

在此链接 [1] 上找到的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

没有明确说明索引是否必须是整数或其他任何东西

最佳答案

这里你想要的不是数组而是对象。

var myObj = {};

myObj['abc'] = 'abc';
myObj['cde'] = 'cde';
myObj['efg'] = 'efg';

// and you can then

delete myObj['abc'];

数组只能有整数索引。

var myArray = new Array();

myArray[0] = 'abc';
myArray[1] = 'cde';
myArray[2] = 'efg';

console.log('before splice:');
console.log(myArray);

myArray.splice(myArray.indexOf('abc'),1);
console.log('after splice:');
console.log(myArray);

关于javascript - 在javascript中使用拼接从数组中删除所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34379844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com