你知道 0 ?? 1等于多少吗?
现在前端发展很快,各种技术和框架层出不穷、百花齐放,很多人都喊学不动啦!事实上JavaScript 作为前端的主要语言,虽然它的发展很快,每年都会出一些新特性,但视乎 JavaScript 开发者的发展速度更快一些,因为很多相对较新的功能都已经有很高的采用率
下面来看看那些具有较高采用率的新特性,2022你应该了解的10个 JS 小技巧
??代替||,用于判断运算符左侧的值为null或undefined时,才返回右侧的值??运算符是 ES2020 引入,也被称为null判断运算符( Nullish coalescing operator)
它的行为类似||,但是更严
||运算符是左边是空字符串或false或0等falsy值,都会返回后侧的值。而??必须运算符左侧的值为null或undefined时,才会返回右侧的值。因此0||1的结果为1,0??1的结果为0
例如
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false
浏览器支持情况

?.简化&&和三元运算符?.也是ES2020 引入,有人称为链判断运算符(optional chaining operator)
?.直接在链式调用的时候判断,判断左侧的对象是否为null或undefined,如果是的,就不再往下运算,返回undefined,如果不是,则返回右侧的值
例如
var street = user.address && user.address.street;
var fooInput = myForm.querySelector('input[name=foo]')
var fooValue = fooInput ? fooInput.value : undefined
// 简化
var street = user.address?.street
var fooValue = myForm.querySelector('input[name=foo]')?.value
注:常见写法
obj?.prop 对象属性obj?.[expr] 对象属性func?.(...args) 函数或对象方法的调用浏览器支持情况

我们可以使用 import 语句初始化的加载依赖项
import defaultExport from "module-name";
import * as name from "module-name";
但是静态引入的import 语句需要依赖于 type="module" 的script标签,而且有的时候我们希望可以根据条件来按需加载模块,比如以下场景:
这个时候我们就可以使用动态引入import(),它跟函数一样可以用于各种地方,返回的是一个 promise
基本使用如下两种形式
//形式 1
import('/modules/my-module.js')
.then((module) => {
// Do something with the module.
});
//形式2
let module = await import('/modules/my-module.js');
浏览器支持情况

其实上面的代码就有用到
let module = await import('/modules/my-module.js')
顶层 await 允许开发者在 async 函数外部使用 await 字段
因此
//以前
(async function () {
await Promise.resolve(console.log('?'));
// → ?
})();
//简化后
await Promise.resolve(console.log('?'));
浏览器支持情况

String.prototype.replaceAll()用法与String.prototype.replace()类似
但是replace仅替换第一次出现的子字符串,而replaceAll会替换所有
例如需要替换所有a为A:
// 以前
console.log('aaa'.replace(/a/g,'A')) //AAA
// 简化后
console.log('aaa'.replaceAll('a','A')) //AAA
浏览器支持情况

为什么使用 Proxy 替代 Object.defineProperty,简单总结Proxy的几点优势
使用也很简单,Proxy本质是构造函数,通过new即可产生对象,它接收两个参数:
target表示的就是要拦截(代理)的目标对象handler是用来定制拦截行为(13种)例如响应式reactive的基本实现:
function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
// 可以做依赖收集
track(target, key)
return target[key]
},
set(target, key, val) {
target[key] = val
// 触发依赖
trigger(target, key)
}
})
}
浏览器支持情况

Promise实例中第一个fulfilled的promise
Promise.any 接收一组Promise实例作为参数
promise 成功,就返回那个已经成功的 promise
promise 成功,就返回一个失败的 promise 和 AggregateError 类型的实例写法推荐
try {
const first = await Promise.any(promises);
// Any of the promises was fulfilled.
} catch (error) {
// All of the promises were rejected.
}
或者
Promise.any(promises).then(
(first) => {
// Any of the promises was fulfilled.
},
(error) => {
// All of the promises were rejected.
}
);
浏览器支持情况

ES2020[1] 引入了一种新的数据类型 BigInt,用来表示任意位数的整数
例如
// 超过 53 个二进制位的数值(相当于 16 个十进制位),无法保持精度
Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
// BigInt
BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false
除了使用BigInt来声明一个大整数,还可以使用数字后面加n的形式,如
1234 // 普通整数1234n // BigInt复制代码
需要了解BigInt数字操作时的支持情况,以免踩坑
| 操作 | 是否支持 |
|---|---|
| 单目 (+) 运算符 | N |
+、*、-、**、% 运算符 |
Y |
| \ 除法运算符 | 带小数的运算会被取整 |
>>> 无符号右移位操作符 |
N |
| 其他位移操作符 | Y |
| 与 Number 混合运算 | N(必须转换为同类型) |
| Math 对象方法 | N |
| Number 与 BigInt 比较(排序) | Y(宽松相等 ==) |
| Boolean 表现 | 类型 Number 对象 |
| JSON 中使用 | N |
浏览器支持情况

Array.prototype.at()接收一个正整数或者负整数作为参数,表示获取指定位置的成员
参数正数就表示顺数第几个,负数表示倒数第几个,这可以很方便的某个数组末尾的元素
例如
var arr = [1, 2, 3, 4, 5]
// 以前获取最后一位
console.log(arr[arr.length-1]) //5
// 简化后
console.log(arr.at(-1)) // 5
#将类字段设为私有在类中通过哈希前缀#标记的字段都将被私有,子类实例将无法继承
例如
class ClassWithPrivateField {
#privateField;
#privateMethod() {
return 'hello world';
}
constructor() {
this.#privateField = 42;
}
}
const instance = new ClassWithPrivateField()
console.log(instance.privateField); //undefined
console.log(instance.privateMethod); //undefined
可以看到,属性privateField和方法privateMethod都被私有化了,在实例中无法获取到
最后
很多新特性都有很多人在用了,特别是??和?.以及动态引入import(),不知道你都用过哪些?
好了,以上就是本文的相关内容,如有问题欢迎指出~?
作者:LBJ
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
动漫制作技巧是很多新人想了解的问题,今天小编就来解答与大家分享一下动漫制作流程,为了帮助有兴趣的同学理解,大多数人会选择动漫培训机构,那么今天小编就带大家来看看动漫制作要掌握哪些技巧?一、动漫作品首先完成草图设计和原型制作。设计草图要有目的、有对象、有步骤、要形象、要简单、符合实际。设计图要一致性,以保证制作的顺利进行。二、原型制作是根据设计图纸和制作材料,可以是手绘也可以是3d软件创建。在此步骤中,要注意的问题是色彩和平面布局。三、动漫制作制作完成后,加工成型。完成不同的表现形式后,就要对设计稿进行加工处理,使加工的难易度降低,并得到一些基本准确的概念,以便于后续的大样、准确的尺寸制定。四、
使用rspec-rails3.0+,测试设置分为spec_helper和rails_helper我注意到生成的spec_helper不需要'rspec/rails'。这会导致zeus崩溃:spec_helper.rb:5:in`':undefinedmethod`configure'forRSpec:Module(NoMethodError)对thisissue最常见的回应是需要'rspec/rails'。但这是否会破坏仅使用spec_helper拆分rails规范和PORO规范的全部目的?或者这无关紧要,因为Zeus无论如何都会预加载Rails?我应该在我的spec_helper中做
我完全不是程序员,正在学习使用Ruby和Rails框架进行编程。我目前正在使用Ruby1.8.7和Rails3.0.3,但我想知道我是否应该升级到Ruby1.9,因为我真的没有任何升级的“遗留”成本。缺点是什么?我是否会遇到与普通gem的兼容性问题,或者甚至其他我不太了解甚至无法预料的问题? 最佳答案 你应该升级。不要坚持从1.8.7开始。如果您发现不支持1.9.2的gem,请避免使用它们(因为它们很可能不被维护)。如果您对gem是否兼容1.9.2有任何疑问,您可以在以下位置查看:http://www.railsplugins.or
我刚刚安装了带有RVM的Ruby2.2.0,并尝试使用它得到了这个:$rvmuse2.2.0--defaultUsing/Users/brandon/.rvm/gems/ruby-2.2.0dyld:Librarynotloaded:/usr/local/lib/libgmp.10.dylibReferencedfrom:/Users/brandon/.rvm/rubies/ruby-2.2.0/bin/rubyReason:Incompatiblelibraryversion:rubyrequiresversion13.0.0orlater,butlibgmp.10.dylibpro
我正在运行Ubuntu11.10并像这样安装Ruby1.9:$sudoapt-getinstallruby1.9rubygems一切都运行良好,但ri似乎有空文档。ri告诉我文档是空的,我必须安装它们。我执行此操作是因为我读到它会有所帮助:$rdoc--all--ri现在,当我尝试打开任何文档时:$riArrayNothingknownaboutArray我搜索的其他所有内容都是一样的。 最佳答案 这个呢?apt-getinstallri1.8编辑或者试试这个:(非rvm)geminstallrdocrdoc-datardoc-da
我已经通过提供MagickWand.h的路径尝试了一切,我安装了命令工具。谁能帮帮我?$geminstallrmagick-v2.13.1Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingrmagick:ERROR:Failedtobuildgemnativeextension./Users/ghazanfarali/.rvm/rubies/ruby-1.8.7-p357/bin/rubyextconf.rbcheckingforRubyversion>=1.8.5...yescheckingfor/
我有1.8.6附带的VanillaMacOSXLeopard。我是RoR的新手,所以会学习网上的教程。在使用更高版本的Ruby时,我是否可能会发现遵循它们的问题?我目前正在查看提到1.8.6和1.8.7的这个-http://www.railstutorial.org/book 最佳答案 RoR教程对两者都适用,但如果您正在学习Ruby,则应该学习1.9。Rails3将不支持1.8.6,所以我会选择1.8.7或1.9。我还推荐使用RVM在Ruby版本之间切换。 关于ruby-on-rail
假设我的Rails项目中有一个设置实例变量的Ruby类。classSomethingdefself.objects@objects||=begin#somelogicthatbuildsanarray,whichisultimatelystoredin@objectsendendend是否可以多次设置@objects?是否有可能在一个请求期间,在上面的begin/end之间执行代码时,可以在第二个请求期间调用此方法?我想这实际上归结为Rails服务器实例如何fork的问题。我应该改用Mutex还是线程同步?例如:classSomethingdefself.objectsreturn@o