Javascript 相当于 PHP 的 list()

发布于 2024-08-16 03:23:04 字数 134 浏览 8 评论 0原文

真的很喜欢这个功能。

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

兔姬 2024-08-23 03:23:04

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

var a = 1;  
var b = 3;  

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

编辑:实际上,如果 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.

var a = 1;  
var b = 3;  

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

EDIT: actually it wouldn't surprise me if the V8 Javascript library (and thus Chrome) supports this. But don't count on it either
Now supported in all modern browsers(except IE, of course).

生生漫 2024-08-23 03:23:04

试试这个:

matches = ['12', 'watt'];
[value, unit] = matches; 

try this:

matches = ['12', 'watt'];
[value, unit] = matches; 
最美的太阳 2024-08-23 03:23:04

ES6 现在通过 数组解构 直接支持此功能。

const matches = ['12', 'watt'];
const [value, unit] = matches;

ES6 does support this directly now via array destructuring.

const matches = ['12', 'watt'];
const [value, unit] = matches;
半窗疏影 2024-08-23 03:23:04

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

首先是实现:

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;  
    }  
}

This is my solution for using List/Explode on Javascript.
Fiddle Working Example

First the implementation :

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

It also allows for scoping the new generated variables :

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

This was accomplished by modifying an the Array prototype.

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;  
    }  
}
夏九 2024-08-23 03:23:04

CoffeeScript 通过以下语法提供解构赋值:

[a, b] = someFunctionReturningAnArray()

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

CoffeeScript offers destructuring assignment with the syntax:

[a, b] = someFunctionReturningAnArray()

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.

乖乖 2024-08-23 03:23:04

由于大多数 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"

Check另


一种方法是向 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"

检查那个小提琴

Since most JavaScript implementations don't yet support that feature, you could simply do it in a more JavaScript-like fashion:

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

Example:

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"

Check the fiddle


An alternative is to add a list-method to Array.prototype (even I wouldn't recommend it):

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:

/**
 * 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"

Check the fiddle for that one

执着的年纪 2024-08-23 03:23:04

这是我的技巧;在不编写函数的情况下尽可能短地完成它。不过,必须注意“这个”的范围:

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];

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

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:

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

Good enough for a laugh. I still assign each variable one at a time:

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

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.

雨的味道风的声音 2024-08-23 03:23:04
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
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);
       }
   }
}

Example:

//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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文