douju1997 2015-02-19 21:43
浏览 81
已采纳

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

Does JavaScript have a language construct or something similar to the php list command? 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($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?

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

  • 写回答

4条回答 默认 最新

  • duanhuai7532 2015-02-20 03:06
    关注

    I've just written a simply function, and it works. Just not exactly like list in 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向