断言在JavaScript中是什么意思?

我见过这样的情况:

assert(function1() && function2() && function3(), "some text");

并且想知道assert()方法做什么。


当前回答

如果你使用webpack,你可以只使用node.js断言库。尽管他们声称它“并不是一个通用的断言库”,但它对于特别的断言似乎已经足够了,而且在Node领域似乎没有竞争对手(Chai是为单元测试而设计的)。

const assert = require('assert');
...
assert(jqXHR.status == 201, "create response should be 201");

你需要使用webpack或browserify才能使用它,所以很明显,这只在那些已经在你的工作流中才有用。

其他回答

Node.js有一个assert函数,你可以导入:

Const assert = require('assert')

正如人们所期望的那样,assert(false)抛出一个错误,assert(false, message)抛出一个带有消息的错误。

其他答案已经指出JS本身没有本机断言函数,在撰写本文(2021年4月)时仍然如此。

正如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');

如果使用现代浏览器或nodejs,则可以使用console。断言(表情,对象)。

欲了解更多信息:

Chrome API参考 Firefox Web控制台 Firebug控制台API IE控制台API 歌剧蜻蜓 Nodejs控制台API

以前的答案可以在性能和兼容性方面得到改进。

检查一次Error对象是否存在,如果没有声明它:

if (typeof Error === "undefined") {
    Error = function(message) {
        this.message = message;
    };
    Error.prototype.message = "";
}

然后,每个断言将检查条件,并始终抛出一个Error对象

function assert(condition, message) {
    if (!condition) throw new Error(message || "Assertion failed");
}

请记住,控制台不会显示真正的错误行号,而是assert函数的行号,这对调试没有用处。