代码之家  ›  专栏  ›  技术社区  ›  Peoray

为什么替换方法会引发错误?

  •  0
  • Peoray  · 技术社区  · 8 年前

    我想替换 myArray “偶数”或“奇数”,但它会引发一个错误, TypeError: val.replace is not a function

    const myArray = [
      [23, 156, 25, 10, 52, 23],
    
      [12, 100, 23, 56, 81, 93],
    
      [42.5, 71, 10, 23, 35, 11, 72, 99],
    
      [11, 100, 99, 102, 13, 8, 12]
    ];
    
    let arr = myArray.map(item => {
      return item.map(val => {
        if (val % 2 == 0) {
          val.toString();
          val.replace(val, "even");
        } else {
          val.replace(val, "odd");
        }
      });
    });
    
    console.log(arr); //TypeError: val.replace is not a function
    
    3 回复  |  直到 8 年前
        1
  •  0
  •   Zohaib Ijaz    8 年前

    您不需要使用替换,只需要映射

    const myArray = [
      [23, 156, 25, 10, 52, 23],
    
      [12, 100, 23, 56, 81, 93],
    
      [42.5, 71, 10, 23, 35, 11, 72, 99],
    
      [11, 100, 99, 102, 13, 8, 12]
    ];
    
    let arr = myArray.map(item => item.map(val => val % 2 == 0 ? 'even' : 'odd'))
    
    console.log(arr);
        2
  •  2
  •   Nina Scholz    8 年前

    您需要返回新值。

    String#replace 返回带有替换值的新字符串,但此处没有字符串。

    const myArray = [
      [23, 156, 25, 10, 52, 23],
      [12, 100, 23, 56, 81, 93],
      [42.5, 71, 10, 23, 35, 11, 72, 99],
      [11, 100, 99, 102, 13, 8, 12]
    ];
    
    let arr = myArray.map(item => {
      return item.map(val => {
        if (val % 2 == 0) {
          return "even";
        } else {
          return "odd";
        }
      });
    });
    
    console.log(arr);
        3
  •  0
  •   Nikhil Aggarwal    8 年前

    您可以尝试以下操作(如果可以被0整除,则检查值;如果可以,则返回 即使 其他的 古怪的 )

    const myArray = [[23, 156, 25, 10, 52, 23], [12, 100, 23, 56, 81, 93], [42.5, 71, 10, 23, 35, 11, 72, 99], [11, 100, 99, 102, 13, 8, 12]];
    
    let arr = myArray.map(item => item.map(val => val%2 === 0 ? "even": "odd"));
    
    console.log(arr);

    或者您可以如下改进代码

    const myArray = [[23, 156, 25, 10, 52, 23], [12, 100, 23, 56, 81, 93], [42.5, 71, 10, 23, 35, 11, 72, 99], [11, 100, 99, 102, 13, 8, 12]];
    
    let arr = myArray.map(item => {
      return item.map(val => {
        if (val % 2 == 0) {
          val = val.toString(); // you need to reassign after toString
          val = val.replace(val, "even"); // you need to reassign after replace
        } else {
          val = val.toString(); // you need to reassign after toString
          val = val.replace(val, "odd"); // you need to reassign after replace
        }
        return val; // finally you need to return the updated value
      });
    });
    
    console.log(arr); //Now the right input will be logged