JavaScript 中的“断言"是什么? [英] What is “assert” in JavaScript?

查看:35
本文介绍了JavaScript 中的“断言"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

assert 在 JavaScript 中是什么意思?

What does assert mean in JavaScript?

我见过类似的东西:

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

并且想知道 assert() 方法的作用.

And would like to know what the method assert() does.

推荐答案

JavaScript 本身没有标准的assert.也许你正在使用一些提供一个的库;例如,如果您使用的是 Node.js,那么您可能正在使用 断言模块.(提供控制台实现控制台API的浏览器和其他环境提供console.assert.)

There is no standard assert in JavaScript itself. Perhaps you're using some library that provides one; for instance, if you're using Node.js, perhaps you're using the assertion module. (Browsers and other environments that offer a console implementing the Console API provide console.assert.)

assert 函数的通常含义是如果传入函数的表达式为假则抛出错误;这是断言检查的一般概念的一部分.通常断言(正如他们所说的那样)仅用于测试"或调试"构建和剥离生产代码.

The usual meaning of an assert function is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.

假设您有一个应该总是接受字符串的函数.您想知道是否有人使用不是字符串的内容调用了该函数(没有像 TypeScript 或 Flow 这样的类型检查层).所以你可能会这样做:

Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string (without having a type checking layer like TypeScript or Flow). So you might do:

assert(typeof argumentName === "string");

...如果条件为假,assert 会抛出错误.

...where assert would throw an error if the condition were false.

一个非常简单的版本如下所示:

A very simple version would look like this:

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

更好的是,利用 Error 对象,它具有收集堆栈跟踪等优点:

Better yet, make use of the Error object, which has the advantage of collecting a stack trace and such:

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

这篇关于JavaScript 中的“断言"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆