LiveScript
LiveScript copied to clipboard
Subscript operator `[]` as function
LiveScript input
([] key) object
([] index) array
([]) key object
([]) index array
JavaScript output
object[key]
array[index]
Doesn't (.)
work?
@vendethiel I already know that there is a (.)
, but (. name) obj
results obj.name
in JavaScript, not obj[name]
— which is what I wanted
How about (.(name)) obj
?
(.name) obj
(.(name)) obj
compiles to
(function(it){
return it.name;
})(obj);
(function(it){
return it[name];
})(obj);
@dk00 Thanks. I didn't know about this. I still think ([] name)
is more intuitive though 😸
If you're trying to achieve a similar result to your example you can use this for now.
arr = [1 2 3]
console.log arr.1
# 2
index = 1
console.log (-> it[index]) arr
# 2
obj =
title: 'I <3 Tomatoes'
description: 'My garden secrets...'
key = 'title'
console.log (-> it[key]) obj
# I <3 Tomatoes
Magically it
is there. 😸
(.[name])
works too, if you prefer square brackets.
Array/object slice works the same way:
(.[1 2 3])
(.{id})