ProgramingTip

PHP의 list ()에 해당하는 Javascript

bestdevel 2020. 12. 25. 10:27
반응형

PHP의 list ()에 해당하는 Javascript


그 기능을 정말 좋아합니다.

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

이에 특허하는 Javascript가 있습니까?


하지만 "새로운"버전의 Javascript : Destructuring assignment-Javascript 1.7이 있습니다. 아마도 Mozilla 기반 브라우저와 Rhino에서만 지원 될 것입니다.

var a = 1;  
var b = 3;  

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

편집 : 실제로 V8 Javascript 라이브러리 (Chrome)가 지원하면 나를 놀라게하지 않을 것입니다. 그러나 의지하지 않습니다 :)


이 시도 :

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

ES6는 이제 배열 분해를 통해이를 직접 지원합니다 .

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

이것은 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.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;  
    }  
}

여기 list()PHPJS의한 실험적 구현이 있습니다 :
https://github.com/kvz/phpjs/blob/master/_experimental/array/list.js


CoffeeScript 는 구문을 사용하여 구조 분해 할당을 제공합니다.

[a, b] = someFunctionReturningAnArray()

이것은 매우 새로운 JavaScript 버전에서 제공되는 기능과 거의 동일합니다. 그러나 CoffeeScript는 IE6의 JavaScript 엔진과 호환되는 JS를 생성 할 수있는 중요한 경우 좋은 옵션입니다.


대부분의 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에 list-method를 추가하는 것입니다.

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"

그 바이올린을 확인하십시오


이것은 내 해킹입니다. 함수를 작성하지 않고도 얻을 수있는 한 짧습니다. 하지만 "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];

이 방법은 훨씬 더 짧습니다. 게다가, 많은 변수가 있다면 그것들은 아마도 배열에 보관되어야하며, 그것들을 모두 개별적으로 선언하는 대신 클로저의 속성이어야합니다.


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

참조 URL : https://stackoverflow.com/questions/1954426/javascript-equivalent-of-phps-list

반응형