断言在JavaScript中是什么意思?
我见过这样的情况:
assert(function1() && function2() && function3(), "some text");
并且想知道assert()方法做什么。
断言在JavaScript中是什么意思?
我见过这样的情况:
assert(function1() && function2() && function3(), "some text");
并且想知道assert()方法做什么。
当前回答
正如t.j.所提到的,JavaScript中没有断言。 但是,有一个名为assert的节点模块,主要用于测试。所以,你可能会看到这样的代码:
const assert = require('assert');
assert(5 > 7);
其他回答
Java有一个断言语句,JVM默认禁用断言验证。它们必须使用命令行参数-enableassertions(或其简写-ea)显式启用,
虽然JavaScript支持console.assert(),但它只是一个日志方法,如果断言失败也不会中断当前过程。
为了把东西放在一起并满足各种需求,这里有一个小的js断言库。
globalThis.assert = (()=> { class AssertionError extends Error { constructor(message) { super(message); this.name = 'AssertionError'; } } let config = { async: true, silent: false }; function assert(condition, message = undefined) { if (!condition) { if (config.silent) { //NOOP } else if (config.async) { console.assert(condition, message || 'assert'); } else { throw new AssertionError(message || 'assertion failed'); } } } assert.config = config; return assert; })(); /* global assert */ Object.assign(assert.config, { // silent: true, // to disable assertion validation async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's) }); let items = [ {id: 1}, {id: 2}, {id: 3} ]; function deleteItem(item) { let index = items.findIndex((e)=> e.id === item.id); assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`); items.splice(index, 1); } console.log('begin'); deleteItem({id: 1}); deleteItem({id: 1}); console.log('end');
如果第一个属性为假,断言将抛出错误消息,而第二个属性是要抛出的消息。
console.assert(condition,message);
有很多评论说断言在JavaScript中不存在,但console.assert()是JavaScript中的断言函数 断言的思想是找出错误发生的原因/位置。
console.assert(document.getElementById("title"), "You have no element with ID 'title'");
console.assert(document.getElementById("image"), "You have no element with ID 'image'");
在这里,您可以根据消息找到错误是什么。 这些错误消息将以红色显示到控制台,就像我们调用了console.error();
你可以使用断言来测试你的函数,例如:
console.assert(myAddFunction(5,8)===(5+8),"Failed on 5 and 8");
注意,条件可以是!= < >等
这通常用于通过提供一些测试用例来测试新创建的函数是否按预期工作,而不是用于生产。
要查看控制台中的更多函数,请执行console.log(console);
JavaScript本身没有标准的断言。也许你使用的库提供了这样的功能;例如,如果你在使用Node.js,也许你在使用断言模块。(提供实现控制台API的控制台的浏览器和其他环境提供console.assert。)
assert函数的通常含义是,如果传入函数的表达式为false,则抛出一个错误;这是断言检查一般概念的一部分。通常断言(正如它们所称)只在“测试”或“调试”构建中使用,并从生产代码中剥离出来。
假设有一个函数总是接受字符串。你会想知道是否有人用不是字符串的东西(没有像TypeScript或Flow这样的类型检查层)调用了这个函数。你可能会这样做:
assert(typeof argumentName === "string");
...如果条件为假,assert将抛出错误。
一个非常简单的版本是这样的:
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
更好的是,利用Error对象,它具有收集堆栈跟踪的优点,例如:
function assert(condition, message) {
if (!condition) {
throw new Error(message || "Assertion failed");
}
}
除了其他选项,如控制台。断言或滚动您自己的,您可以使用不变式。它有几个独特的特点:
它支持格式化的错误消息(使用%s说明符)。 在生产环境中(由Node.js或Webpack环境决定),错误消息是可选的,允许(稍微)较小的.js。
正如t.j.所提到的,JavaScript中没有断言。 但是,有一个名为assert的节点模块,主要用于测试。所以,你可能会看到这样的代码:
const assert = require('assert');
assert(5 > 7);