codecamp

CoffeeScript 使用数组来交换变量

使用数组来交换变量

问题

你想通过数组来交换变量。

解决方案

使用CoffeeScript的解构赋值语法:

a = 1
b = 3

[a, b] = [b, a]

a
# => 3

b
# => 1

讨论

解构赋值可以不依赖临时变量实现变量值的交换。

这种语法特别适合在遍历数组的时候只想迭代最短数组的情况:

ray1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
ray2 = [ 5, 9, 14, 20 ]

intersection = (a, b) ->
  [a, b] = [b, a] if a.length > b.length
  value for value in a when value in b

intersection ray1, ray2
# => [ 5, 9 ]

intersection ray2, ray1
# => [ 5, 9 ]
CoffeeScript 检测每个元素
CoffeeScript 对象数组
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

CoffeeScript 数据库

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }