Angular2 IndexOf 查找和删除数组值
Angular2 IndexOf Finding and Deleting Array Value
您好,我正在尝试使用 Angular2 和 Typescript 删除数组中的某个索引。我想从值中检索索引。
我的数组声明正常...
RightList = [
'Fourth property',
'Fifth property',
'Sixth property',
]
我从设置删除功能的基本前提开始。
removeSel(llist: ListComponent, rlist:ListComponent){
this.selectedllist = llist;
console.log(JSON.stringify(this.selectedllist)); // what is to be searched turned into a string so that it may actually be used
我的 console.log 或 JSON.Stringify 告诉我我将尝试删除的值是 "Sixth property"。但是,当我尝试使用以下代码在我的数组中查找此值时。它 returns -1 这意味着在数组中找不到我的值。
var rightDel = this.RightList.indexOf((JSON.stringify(this.selectedllist))); // -1 is not found 1 = found
console.log(rightDel);
在我到控制台的输出中,它return要搜索的项目但在数组中找不到该项目
CONSOLE OUTPUT:
"Sixth property" // Item to be searched for
-1 // not found
我执行的搜索数组的函数有问题吗?
当然 indexOf 不会在数组中找到你的项目,因为
JSON.stringify(this.selectedllist) !== this.selectedllist
这是因为 JSON 字符串化字符串对文字周围的引号进行编码,而原始字符串没有。很容易测试:
var a = 'test';
console.log( JSON.stringify(a), a, JSON.stringify(a) === a )
删除 JSON.stringify
它应该可以工作。通常,要将某些内容转换为 String 类型,您应该使用它的 .toString()
方法,或者简单地将此内容包装到 String(something)
.
您好,我正在尝试使用 Angular2 和 Typescript 删除数组中的某个索引。我想从值中检索索引。
我的数组声明正常...
RightList = [
'Fourth property',
'Fifth property',
'Sixth property',
]
我从设置删除功能的基本前提开始。
removeSel(llist: ListComponent, rlist:ListComponent){
this.selectedllist = llist;
console.log(JSON.stringify(this.selectedllist)); // what is to be searched turned into a string so that it may actually be used
我的 console.log 或 JSON.Stringify 告诉我我将尝试删除的值是 "Sixth property"。但是,当我尝试使用以下代码在我的数组中查找此值时。它 returns -1 这意味着在数组中找不到我的值。
var rightDel = this.RightList.indexOf((JSON.stringify(this.selectedllist))); // -1 is not found 1 = found
console.log(rightDel);
在我到控制台的输出中,它return要搜索的项目但在数组中找不到该项目
CONSOLE OUTPUT:
"Sixth property" // Item to be searched for
-1 // not found
我执行的搜索数组的函数有问题吗?
当然 indexOf 不会在数组中找到你的项目,因为
JSON.stringify(this.selectedllist) !== this.selectedllist
这是因为 JSON 字符串化字符串对文字周围的引号进行编码,而原始字符串没有。很容易测试:
var a = 'test';
console.log( JSON.stringify(a), a, JSON.stringify(a) === a )
删除 JSON.stringify
它应该可以工作。通常,要将某些内容转换为 String 类型,您应该使用它的 .toString()
方法,或者简单地将此内容包装到 String(something)
.