Javascript 相当于 PHP 的 list()
真的很喜欢这个功能。
$matches = array('12', 'watt');
list($value, $unit) = $matches;
Javascript 有等价的吗?
Really like that function.
$matches = array('12', 'watt');
list($value, $unit) = $matches;
Is there a Javascript equivalent of that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
在 Javascript 的“较新”版本中,有:解构赋值 - Javascript 1.7。它可能仅在基于 Mozilla 的浏览器中受支持,也可能在 Rhino 中受支持。
编辑:
实际上,如果 V8 Javascript 库(以及 Chrome)支持这一点,我不会感到惊讶。但也不要指望它现在所有现代浏览器都支持(除了IE,当然)。
There is, in 'newer' versions of Javascript: Destructuring assignment - Javascript 1.7. It's probably only supported in Mozilla-based browsers, and maybe in Rhino.
EDIT:
actually it wouldn't surprise me if the V8 Javascript library (and thus Chrome) supports this. But don't count on it eitherNow supported in all modern browsers(except IE, of course).
试试这个:
try this:
ES6 现在通过 数组解构 直接支持此功能。
ES6 does support this directly now via array destructuring.
这是我在 Javascript 上使用 List/Explode 的解决方案。
Fiddle 工作示例
首先是实现:
它还允许确定新生成的变量的范围:
这已完成通过修改数组原型。
This is my solution for using List/Explode on Javascript.
Fiddle Working Example
First the implementation :
It also allows for scoping the new generated variables :
This was accomplished by modifying an the Array prototype.
这里有 PHPJS 的
list()
实验性实现:https://github.com/kvz/phpjs/blob/master /_experimental/array/list.js
There is a experimental implementation of
list()
by PHPJS here:https://github.com/kvz/phpjs/blob/master/_experimental/array/list.js
CoffeeScript 通过以下语法提供解构赋值:
这与非常新的 JavaScript 版本中提供的功能几乎相同。然而,CoffeeScript 生成的编译 JS 甚至与 IE6 的 JavaScript 引擎兼容,因此如果兼容性至关重要,那么它是一个不错的选择。
CoffeeScript offers destructuring assignment with the syntax:
This is pretty much identical to the feature offered in very new JavaScript versions. However, CoffeeScript produces compiled JS that is compatible even with IE6's JavaScript engine, and therefore it's a good option if compatibility is vital.
由于大多数 JavaScript 实现尚不支持该功能,因此您可以简单地以更像 JavaScript 的方式执行此操作:
示例:
Check另
一种方法是向 Array.prototype 添加列表方法(即使我不推荐它):
示例:
检查那个小提琴
Since most JavaScript implementations don't yet support that feature, you could simply do it in a more JavaScript-like fashion:
Example:
Check the fiddle
An alternative is to add a list-method to Array.prototype (even I wouldn't recommend it):
Example:
Check the fiddle for that one
这是我的技巧;在不编写函数的情况下尽可能短地完成它。不过,必须注意“这个”的范围:
足以让人笑了。我仍然一次为每个变量分配一个:
这样会短得多。此外,如果你有一堆变量,它们可能应该保存在数组中,或者更好的是它们应该是闭包的属性,而不是单独声明它们。
This is my hack at it; as short as I could get it without writing a function to do it. Gotta be careful of the scope of "this" though:
Good enough for a laugh. I still assign each variable one at a time:
It's much shorter this way. Besides, if you've got a bunch of variables they should probably be kept in the array, or even better they should be properties of a closure, instead of declaring them all separately.
例子:
Example: