如何抛出异常?

我有一个将二维数组转换为 csv 格式的函数。该函数应仅适用于文本和数字,否则会显示错误。当我启动该功能时,首先进行检查并且该功能完成。如何使该功能继续工作?


function arraysToCsv(data) {

  for(let i = 0; i < data.length; i++){

    let value = data[i];

    for(let j = 0; j < value.length; j++){

      if(typeof value[j] !== 'string' || typeof value[j] !== 'number')

        throw new Error('Unexpected value');

      let result = value[j].replace(/"/g, '""');

      if (result.search(/("|,|\n)/g) >= 0){

          result = '"' + result + '"';

      }

      return result.join(',') + '\n';

  }

  }

}


森栏
浏览 124回答 2
2回答

阿波罗的战车

如果您的函数必须仅使用数字或字符串,则您将其插入 if continue 语句中。if(typeof value[j] !== 'string' || typeof value[j] !== 'number') 继续;如果要显示错误消息,可以使用警报,也可以通过 console.log 将其写入控制台,在 continue 语句之前。我希望对你有所帮助。

肥皂起泡泡

function arraysToCsv(data) {&nbsp; for(let i = 0; i < data.length; i++){&nbsp; &nbsp; let value = data[i];&nbsp; &nbsp; for(let j = 0; j < value.length; j++){&nbsp; &nbsp; &nbsp; let type = typeof(value[j]);&nbsp; &nbsp; &nbsp; let isStringOrNumber = type === 'string' || type === 'number';&nbsp; &nbsp; &nbsp; if(!isStringOrNumber)&nbsp; &nbsp; &nbsp; &nbsp; throw new Error('Unexpected value');&nbsp; &nbsp; &nbsp; let result = value[j].replace(/"/g, '""');&nbsp; &nbsp; &nbsp; if (result.search(/("|,|\n)/g) >= 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = '"' + result + '"';&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return result.join(',') + '\n';&nbsp; }&nbsp; }}或者(使用和)...function arraysToCsv(data) {&nbsp; for(let i = 0; i < data.length; i++){&nbsp; &nbsp; let value = data[i];&nbsp; &nbsp; for(let j = 0; j < value.length; j++){&nbsp; &nbsp; &nbsp; let type = typeof(value[j]);&nbsp; &nbsp; &nbsp; let isNotStringOrNumber = type !== 'string' && type !== 'number';&nbsp; &nbsp; &nbsp; if(isNotStringOrNumber)&nbsp; &nbsp; &nbsp; &nbsp; throw new Error('Unexpected value');&nbsp; &nbsp; &nbsp; let result = value[j].replace(/"/g, '""');&nbsp; &nbsp; &nbsp; if (result.search(/("|,|\n)/g) >= 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = '"' + result + '"';&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return result.join(',') + '\n';&nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript