当前位置:网站首页>逗号操作符你有用过吗?
逗号操作符你有用过吗?
2022-07-27 14:39:00 【前行的枫】
什么是逗号操作符?mdn解释: 对它的每个操作数求值(从左到右),并返回最后一个操作数的值。翻译:如(x,y),从左到右分别计算x和y,最后返回y
mdn案例:
let x = 1;
x = (x++, x);
console.log(x); // 2
是不是感觉好像这个逗号操作符没什么作用啊?存在就有意义,在一些场景还是有用的。
举个栗子:(用reduce可以实现reverse)
var arr = [1,2,3,4,5]
var result = arr.reduce((t,v)=> (t.unshift(v),t),[])
console.log(result) // [5,4,3,2,1]
reduce又是什么?mdn解释:reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。还是翻译一下吧:好吧,翻译不来,反正就是累加器的作用
reduce(func,initValue)
参数:
func:回调函数,并且有四个参数acc:累加器(说白了就是能拿到上一次的返回值)cur:当前值idx:当前索引oarr:原数组
initValue:初始值
再来看看刚刚那个栗子:
var arr = [1,2,3,4,5]
var result = arr.reduce((t,v)=> (t.unshift(v),t),[])
console.log(result) // [5,4,3,2,1]
可能会问直接这样不就好了:var result = arr.reduce((t,v)=> t.unshift(v),[])
来吧看报错:Uncaught TypeError: t.unshift is not a function
unshift方法返回的是数组的长度,那么下一次的t就是number类型而不是数组,所以会这个报错。
拆开这个写法就是:
var result = arr.reduce((t,v)=> {
t.unshift(v);
return t;
},[])
那么按照逗号操作符的运算就可以简化写法了:
var result = arr.reduce((t,v)=> (t.unshift(v),t),[])
边栏推荐
- First acquaintance with MySQL database
- Go language slow start - package
- 剑指 Offer 51. 数组中的逆序对
- On juicefs
- 减小程序rom ram,gcc -ffunction-sections -fdata-sections -Wl,–gc-sections 参数详解
- 传音控股披露被华为起诉一事:已立案,涉案金额2000万元
- 单机高并发模型设计
- JS operation DOM node
- Short video mall system, system prompt box, confirmation box, click blank to close the pop-up box
- [sword finger offer] interview question 54: the k-largest node of the binary search tree
猜你喜欢

Half find

SQL multi table query

leetcode234题-简单方法判断回文链表

解决MT7620不断循环uboot(LZMA ERROR 1 - must RESET board to recover)

Clickhouse 20.x distributed table testing and chproxy deployment (II)

What format is this data returned from the background

C language: minesweeping games

C语言:函数栈帧

单机高并发模型设计

keil 采用 makefile 实现编译
随机推荐
It is said that the US government will issue sales licenses to Huawei to some US enterprises!
Network principle (2) -- network development
数据表的约束以及设计、联合查询——8千字攻略+题目练习解答
文字批量替换功能
Openwrt 新增平台编译
线程中死锁的成因及解决方案
初识MySQL数据库
数组名是首元素地址吗?
js操作dom节点
[regular expression] single character matching
makefile 中指定程序运行时加载的库文件路径
Six capabilities of test and development
C language: custom type
C: What is the return value (revolution) in a function
Binary Insertion Sort
Leetcode-1: sum of two numbers
[tensorboard] oserror: [errno 22] invalid argument processing
折半查找
keil 采用 makefile 实现编译
JS operation DOM node