首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP的list()的Javascript等价物

PHP的list()的Javascript等价物
EN

Stack Overflow用户
提问于 2009-12-24 02:11:53
回答 7查看 38.7K关注 0票数 67

真的很喜欢这个函数。

$matches = array('12', 'watt');
list($value, $unit) = $matches;

有没有与之相对应的Javascript?

EN

回答 7

Stack Overflow用户

发布于 2011-06-16 06:22:41

试试这个:

matches = ['12', 'watt'];
[value, unit] = matches; 
票数 20
EN

Stack Overflow用户

发布于 2015-11-27 20:02:26

ES6现在通过array destructuring直接支持这一点。

const matches = ['12', 'watt'];
const [value, unit] = matches;
票数 19
EN

Stack Overflow用户

发布于 2013-07-25 01:55:24

这是我在Javascript上使用列表/分解的解决方案。Fiddle Working Example

首先是实现:

var dateMonth = "04/15";
dateMonth.split("/").list("month","day", "year");
month == "04";
day == "15";
year == null;

它还允许确定新生成的变量的作用域:

var scoped = (function()
{ 
    var dateMonth = "07/24/2013"; 
    dateMonth.split("/").list("month","day", "year", this);
    this.month == "07";
    this.day == "24";
    this.year == "2013";
})();

这是通过修改阵列原型来实现的。

Array.prototype.list = function()
{
    var 
        limit = this.length,
        orphans = arguments.length - limit,
        scope = orphans > 0  && typeof(arguments[arguments.length-1]) != "string" ? arguments[arguments.length-1] : window 
    ;

    while(limit--) scope[arguments[limit]] = this[limit];

    if(scope != window) orphans--;

    if(orphans > 0)
    {
        orphans += this.length;
        while(orphans-- > this.length) scope[arguments[orphans]] = null;  
    }  
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1954426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档