69

真的很喜欢这个功能。

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

是否有与之等效的Javascript?

4

9 回答 9

60

在 Javascript 的“较新”版本中有:解构赋值 - Javascript 1.7。它可能只在基于 Mozilla 的浏览器中支持,也许在 Rhino 中。

var a = 1;  
var b = 3;  

[a, b] = [b, a];  

编辑:实际上,如果 V8 Javascript 库(以及 Chrome)支持这一点,我不会感到惊讶。但也不要指望它 现在所有现代浏览器都支持(当然,除了 IE)。

于 2009-12-23T18:16:25.210 回答
20

尝试这个:

matches = ['12', 'watt'];
[value, unit] = matches; 
于 2011-06-15T22:22:40.680 回答
19

ES6 现在通过数组解构直接支持这一点。

const matches = ['12', 'watt'];
const [value, unit] = matches;
于 2015-11-27T12:02:25.953 回答
4

这是我在 Javascript 上使用 List/Explode 的解决方案。 小提琴工作示例

首先实现:

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 原型来完成的。

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;  
    }  
}
于 2013-07-24T17:55:23.513 回答
2

PHPJS在这里有一个实验性的实现list():https: //github.com/kvz/phpjs/blob/master/_experimental/array/list.js

于 2011-03-24T10:42:54.287 回答
2

CoffeeScript使用以下语法提供解构赋值:

[a, b] = someFunctionReturningAnArray()

这与非常新的 JavaScript 版本中提供的功能几乎相同。但是,CoffeeScript 生成的编译后的 JS 甚至与 IE6 的 JavaScript 引擎兼容,因此如果兼容性至关重要,它是一个不错的选择。

于 2012-12-11T03:15:52.080 回答
1

由于大多数 JavaScript 实现还不支持该功能,您可以简单地以更类似于 JavaScript 的方式来实现:

function list(){
    var args = arguments;
    return function(array){
        var obj = {};
        for(i=0; i<args.length; i++){
            obj[args[i]] = array[i];
        }
        return obj;
    };
}

例子:

var array = ['GET', '/users', 'UserController'];
var obj = {};

obj = list('method', 'route', 'controller')(array);

console.log(obj.method);        // "GET"
console.log(obj.route);         // "/users"
console.log(obj.controller);    // "UserController"

检查小提琴


另一种方法是向 Array.prototype 添加一个列表方法(即使我不推荐它):

Array.prototype.list = function(){
    var i, obj = {};
    for(i=0; i<arguments.length; i++){
        obj[arguments[i]] = this[i];
    }
    // if you do this, you pass to the dark side `,:,´
    this.props = obj;
    return obj;
};

例子:

/**
 * Example 1: use Array.prototype.props
 */

var array = ['GET', '/users', 'UserController'];
array.list('method', 'route', 'controller');

console.log(array.props.method);        // "GET"
console.log(array.props.route);         // "/users"
console.log(array.props.controller);    // "UserController"

/**
 * Example 2: use the return value
 */

var array = ['GET', '/users', 'UserController'];
var props = array.list('method', 'route', 'controller');

console.log(props.method);      // "GET"
console.log(props.route);       // "/users"
console.log(props.controller);  // "UserController"

检查那个小提琴

于 2015-11-27T11:02:34.377 回答
0

这是我的窍门;尽可能短,而无需编写函数来完成它。不过要注意“this”的范围:

list = ["a","b","c"];
vals = [1,2,3];
for(var i in vals)this[list[i]]=vals[i];
console.log(a,b,c);

足以笑出声来。我仍然一次为每个变量分配一个:

a=vals[0];
b=vals[1];
c=vals[2];

这种方式要短得多。此外,如果你有一堆变量,它们可能应该保存在数组中,或者更好的是它们应该是闭包的属性,而不是单独声明它们。

于 2015-03-22T04:03:29.300 回答
-2
function list(fn,array){
    if(fn.length && array.length){
        for(var i=0;i<array.length;i++){
            var applyArray = [];
            for(var j=0;j<array[i].length;j++){
                fn[j] = array[i][j];
                applyArray.push(fn[j]);
            }
        fn.apply(this,applyArray);
       }
   }
}

例子:

//array array mixture for composure
var arrayMixture = [ ["coffee","sugar","milk"], ["tea","sugar","honey"] ];
//call our function


list(function(treat,addin,addin2){
    console.log("I like "+treat+" with " + addin + " and " + addin2);
},arrayMixture);


//output:
//I like coffee with sugar and milk
//I like tea with sugar and honey
于 2015-09-10T21:22:39.330 回答