为什么我的替换方法会抛出错误?

时间:2018-05-23 12:07:13

标签: javascript

我想将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 个答案:

答案 0 :(得分:2)

您需要返回新值。

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);




答案 1 :(得分: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);




答案 2 :(得分:0)

你可以尝试跟随(检查值是否可被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