Javascript 未捕获类型错误:无法读取属性';指数';未定义的对象

Javascript 未捕获类型错误:无法读取属性';指数';未定义的对象,javascript,Javascript,首先,我不是一个前端开发人员,我对JavaScript不太了解,所以请耐心回答我的问题,我会很感激,但我需要解决这个“典型”错误,但我在google中找不到,stackoverflow如何解决,比方说在代码中,它以某种方式工作,但在当前解决方案出现之前,它是这样的: Where是正确的,但它不是“漂亮的”,所以我尝试重构这段代码,使其更干净、更简单 if ( Object.values(this.searchParams.data)[0] === 'price_desc' ||

首先,我不是一个前端开发人员,我对JavaScript不太了解,所以请耐心回答我的问题,我会很感激,但我需要解决这个“典型”错误,但我在google中找不到,stackoverflow如何解决,比方说在代码中,它以某种方式工作,但在当前解决方案出现之前,它是这样的:

Where是正确的,但它不是“漂亮的”,所以我尝试重构这段代码,使其更干净、更简单

if (
      Object.values(this.searchParams.data)[0] === 'price_desc' ||
      Object.values(this.searchParams.data)[0] === 'price_asc'
    ) {
      // Do nothing
    } else if (!this.searchParams.data.price) {
      this.getProducts();
    }
关于这一点:

考虑到它是像
{sortBy:“price\u asc”}
{sortBy:“price\u desc”}

在终端中显示:

但是我们使用ES5,我不能使用
this.searchSortBy.includes()
,因为它不起作用

下面是我的代码:

var SponsoredProducts = (function() {
  function SponsoredProducts(
    this.searchParams = window.getSearch();

    this.searchSortBy = Object.values(this.searchParams.data)[0];

    console.log(this.searchParams.data.sortBy);
    console.log('-----------------------');
    console.log(this.searchSortBy);
    console.log('-----------1-----------');
    console.log(typeof this.searchSortBy.indexOf('price') === undefined);
    console.log('-----------2-----------');
    console.log(this.searchSortBy.indexOf('price') === "undefined");
    console.log('-----------3-----------');
    console.log(typeof this.searchSortBy.indexOf('price') == 
    if (!this.searchParams.data.price &&  String(this.searchSortBy).indexOf('price') == "-1") {
      this.getProducts();
    }

  }
但我经常遇到这样的问题:uncaughttypeerror:无法读取未定义的属性'indexOf'

那么有一个合适的解决方案吗?如果有人能帮助我,我将非常感激。

找到了一个解决方案:

它不起作用的原因是因为我没有定义值为空/未定义的时间,所以我添加了
| |“
来创建一些即使是空的内容,以便
索引的
可以检查返回的内容
-1

this.searchSortBy = this.searchParams.data.sortBy || '';

 if (
   !this.searchParams.data.price &&
   this.searchSortBy.indexOf('price') < 0
 ) {
   this.getProducts();
 }
this.searchSortBy=this.searchParams.data.sortBy | |'';
如果(
!this.searchParams.data.price&&
此.searchSortBy.indexOf('price')<0
) {
这个.getProducts();
}

IndexOf永远不会返回undefined,只有当它不是所用字符串的索引时才返回-1。代码中存在多个语法错误。请发布显示您的问题的工作代码。不要将您的答案编辑到问题中。如果你认为答案对某人有帮助,可以添加答案,也可以删除你的问题。