javascript - 未通过预期值时设置函数的默认值
问题描述
我想为函数没有传递任何内容的情况制作一个处理程序,例如var v = Vector()
,与例如相反Vector(2,5,1)
。
var Vector3 = function(x, y, z) {
this.x = x; this.y = y; this.z = z;
if (Vector3() === null)
{
this.x = 0;
this.y = 0;
this.z = 0;
}
解决方案
您可以使用默认参数,当它们未传递时默认为 0:
function Vector(x=0, y=0, z=0) {
this.x = x;
this.y = y;
this.z = z;
}
console.log(new Vector(2,5,1));
console.log(new Vector());
推荐阅读
- python - How does this while-loop compute? (x = function(x))
- keras - 如何在谷歌 colab 中找到 keras.json 文件?
- node.js - 将 Strapi API 部署到 Plesk
- java - X509TrustManager 的 checkServerTrusted 方法中验证了哪些所有参数?
- python - 在 python 的子目录中对具有字母数字字符的列表作为文件名进行排序
- objective-c - VSCode 显示 Objective-C 头文件的“无法识别的令牌”
- sql-server - 将 SQL Server 2016 兼容级别更改为 2012
- angular - ngI18nClosureMode 未定义
- java - 随机线程的多线程
- javascript - d3.each() 一次存储一个值,而不是一次存储所有值