Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 比较typescript中的两个字符串_Javascript_Arrays - Fatal编程技术网

Javascript 比较typescript中的两个字符串

Javascript 比较typescript中的两个字符串,javascript,arrays,Javascript,Arrays,x.name和imgname具有相同的类型(字符串)和相同的值“comcardpro_capsule_model_2”。但是为什么findIndex()函数返回-1呢? 请给我解释一下 findPicture(imgname): number { return this.info.comcardList.findIndex(x => { x.name === imgname; // result in console: console.log

x.name和imgname具有相同的类型(字符串)和相同的值“comcardpro_capsule_model_2”。但是为什么findIndex()函数返回-1呢? 请给我解释一下

findPicture(imgname): number {
   return this.info.comcardList.findIndex(x => {
      x.name === imgname;          // result in console:
      console.log(imgname)         // comcardpro_capsule_model_2
      console.log(typeof imgname)  // string
      console.log(typeof x.name)   // string
      console.log(x.name);         // comcardpro_capsule_model_2
   })
  }

预期结果将是数组中元素的索引而不是-1。

您的
findIndex
回调总是返回未定义的,您应该返回x.name==imgname

findIndex
函数的基本功能如下

if (findIndexCallback(element)) return index;
对于数组的每个元素。因此,如果函数不返回任何内容(
undefined
),则返回表示“未找到”的
-1
的回退值


有关完整文档,请参阅。

您需要在findIndex上添加返回语句

findPicture(imgname):编号{
返回此.info.comcardList.findIndex(x=>{
返回x.name==imgname;//控制台中的结果:
})
}

您需要从findIndex函数返回结果

findPicture(imgname): number {
    return this.info.comcardList.findIndex(x => {
    return x.name === imgname;
    });
 }

您需要添加return语句,因为您没有返回比较结果。这就是这里发生的一切,很有效,谢谢。但是你能解释一下为什么我们不能删除
returnx.name==imgname中的“return”单语句/无括号箭头函数不需要返回语句,因为它是隐式的<代码>()=>5
是一个返回5的函数
()=>{5;}
是一个返回未定义的函数。如果你的函数只是
x=>x.name==imgname
它也会工作;常量指数=水果。findIndex(水果=>水果==“蓝莓”);console.log(索引);//3.日志(水果[索引];//蓝莓