简体   繁体   English

JavaScript 是否具有类似于 php list 命令的语言结构?

[英]Does JavaScript have a language construct similar to the php list command?

Does JavaScript have a language construct or something similar to the php list command? JavaScript 是否有语言结构或类似于 php list 命令的东西? http://php.net/manual/en/function.list.php http://php.net/manual/en/function.list.php

This command will assign the values of an array to variables in a single statement.此命令将在单个语句中将数组的值分配给变量。 For example, given the array:例如,给定数组:

$info = array('Coffee', 'brown', 'caffeine');

The list command will assign each of the array element values to named variables: list 命令会将每个数组元素值分配给命名变量:

list($drink, $color, $power) = $info;

such that:使得:

   echo "$drink is $color and $power makes it special."; // results in:

   Coffee is brown and caffeine makes it special.

So this is an easy way to assign values to many variables in one statement.所以这是一种在一个语句中为多个变量赋值的简单方法。

Does JavaScript have something equivalent where each variable does not have to be assigned separately? JavaScript 是否有一些等效的东西,其中每个变量不必单独分配?

Is there a way to do this using either an object's properties or an array's elements?有没有办法使用对象的属性或数组的元素来做到这一点? If not, can a function be written that would do it?如果没有,是否可以编写一个函数来做到这一点? If the only way to do this is via a function, then the function would need access to the scope where the variables are defined.如果执行此操作的唯一方法是通过函数,则该函数将需要访问定义变量的范围。

I tried the solutions in this five year old question: Javascript equivalent of PHP's list() , but they don't work.我在这个五年前的问题中尝试了解决方案: Javascript 等效于 PHP 的 list() ,但它们不起作用。 The Array prototype change fails to assign the variables in my node.js environment and the left handed array assignment is a reference error in Chrome.数组原型更改无法在我的 node.js 环境中分配变量,左手数组分配是 Chrome 中的引用错误。 There is talk about an experimental new technique, but the talk is several years old.有关于一种实验性新技术的讨论,但这种讨论已有好几年了。 I'd like to know if there is a solution to this better than those listed in the linked question.我想知道是否有比链接问题中列出的解决方案更好的解决方案。

I've just written a simply function, and it works.我刚刚写了一个简单的函数,它可以工作。 Just not exactly like list in php.只是不完全像 php 中的列表。 Here it is这里是

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

It's nothing spectacular but if you are looking for something simple and use case for yourself there it is.这没什么了不起的,但如果您正在寻找简单的东西并为自己使用案例,那就是。

How to use this?这个怎么用?

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

Hope that's what you were looking for希望这就是你要找的

This is called "destructuring assignment" in ECMAScript 6. Mozilla Developer Network has some examples:这在 ECMAScript 6 中称为“解构赋值”。 Mozilla 开发者网络有一些例子:

var a, b;
[a, b] = [1, 2]
{a, b} = {a:1, b:2}

It is supported in Node.js since at least version 8, and also in some browsers, as you can see in this ECMAScript compatibility table .至少从版本 8 开始,Node.js 以及某些浏览器都支持它,正如您在此ECMAScript 兼容性表中所见。 You can still use it if you transpile your code to ECMAScript 5 with something like Babel .如果您使用Babel 之类的东西将代码转换为 ECMAScript 5,您仍然可以使用它。

There's a experimental function written by php.js that tries to adapt php's list function to js, maybe you can built on this: php.js写了一个实验性的函数,尝试将 php 的 list 函数适配到 js,也许你可以以此为基础:

function list() {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // %        note 1: Only works in global context and deviates (by necessity) from
  // %        note 1: PHP version by adding the array (which in PHP is an rvalue
  // %        note 1: separate from the list() lvalue) as the last argument
  // *     example 1: var drink, color, power;
  // *     example 1: list('drink', 'color', 'power', ['coffee', 'brown', 'caffeine']);
  // *     example 1: drink +' is '+color+' and '+power+' makes it special.\n';
  // *     returns 1: 'coffee is brown and caffeine makes it special.\n'

  var i = 0, arr = [];

  arr = arguments[arguments.length - 1];

  if (arr && typeof arr === 'object' && arr.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
    return arr.list.apply(arr, Array.prototype.slice.call(arguments, 0, -1));
  }
  if (arr && typeof arr === 'object' && arr.length && !arr.propertyIsEnumerable('length')) {
    for (i = 0; i < arr.length; i++) {
      this.window[arguments[i]] = arr[i];
    }
  }
  else {
    for (i in arr) {
      if (i.length === parseInt(i).toString().length && parseInt(i) < arguments.length - 1) {
        this.window[arguments[i]] = arr[i];
      }
    }
  }

  return arr;
}

I think the accepted answer by EasyBB could be simplified greatly for cases where you don't have nested arrays.我认为对于没有嵌套数组的情况, EasyBB接受的答案可以大大简化。

var info = [ "Coffee", "brown", "caffeine" ];

(function(drink, color, power) {
    console.log(drink + " is " + color + " and " + power + " makes it special.");
}.apply(this, info));

Now you don't have to define an extra function to get the job done.现在您不必定义额外的函数来完成工作。 Of course, it will be much nicer when ES6 is adopted and we can use array destructuring.当然,如果采用 ES6 会更好,我们可以使用数组解构。 In the meantime, I would probably just use the old fashioned var drink = info[0], color = info[1], power = info[2];与此同时,我可能只会使用老式的var drink = info[0], color = info[1], power = info[2]; ; ; it's more readable and uses less memory.它更具可读性并使用更少的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM