![]() |
机灵的牛肉面 · 国家金融监督管理总局· 2 周前 · |
![]() |
睿智的海龟 · NiFi:将文件内容存储在内存或全局变量中- ...· 10 月前 · |
![]() |
文质彬彬的打火机 · 【月听】刘瑜:一个人要像一支队伍-新华网· 11 月前 · |
![]() |
爱吹牛的柑橘 · 朱锦尔:世界唯一一位等级分在2500分以上的 ...· 12 月前 · |
![]() |
面冷心慈的手套 · 1—7月全市社零总额同比增长8.3% ...· 1 年前 · |
我有一个在TypeScript中创建的数组,它有一个我用作键的属性。如果我有那个钥匙,我怎么才能从里面删除一个项目呢?
与在JavaScript中使用的方法相同。
delete myArray[key];
请注意,这会将元素设置为
undefined
。
最好使用
Array.prototype.splice
函数:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}
您可以在数组上使用
splice
方法来删除元素。
例如,如果您有一个名为
arr
的数组,请使用以下代码:
arr.splice(2, 1);
因此,这里索引为2的元素将是起点,参数2将确定要删除的元素的数量。
如果要删除名为
arr
的数组的最后一个元素,请执行以下操作:
arr.splice(arr.length-1, 1);
这将返回删除了最后一个元素的arr。
示例:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
这对我很有效。
您的数组:
DummyArray: any = [
{ "id": 1, "name": 'A' },
{ "id": 2, "name": 'B' },
{ "id": 3, "name": 'C' },
{ "id": 4, "name": 'D' }
]
功能:
remove() {
this.DummyArray = this.DummyArray.filter(item => item !== item);
}
注意:此函数删除数组中的所有对象。如果你想从数组中删除一个特定的对象,那么使用这个方法:
remove(id) {
this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}
我们可以使用
filter
和
includes
来实现逻辑
const checkAlpha2Code = ['BD', 'NZ', 'IN']
let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']
* Returns the modified array countryAlpha2Code
* after removing elements which matches with the checkAlpha2Code
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
return !checkAlpha2Code.includes(alpha2code);
console.log(countryAlpha2Code)
// Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ]
// Resetting the values again
countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']
* Returns the modified array countryAlpha2Code
* which only matches elements with the checkAlpha2Code
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
return checkAlpha2Code.includes(alpha2code);
console.log(countryAlpha2Code)