简体   繁体   中英

use anonymous function for other function's parameter in javascript

i'm beginner on javascript. please watch my code.

function map(func, ary)
{   var i =0;
var array1 = ary;
while(ary[i]!=NULL){
    array1[i] = func(ary[i]);
    i++;
}
document.write('[' + array1[0] +',' +array1[1]+']'); //just for check result
}

map(function(x) {return (x*4)/2;},[1,3,5,7]);

I want operate that " map(function(x) {return (x*4)/2;},[1,3,5,7]); " in javascript.

How can i operate that code? please help me detail.

I don't understand what you really want to ask. Your code works.
Use null, false, true instead of NULL FALSE TRUE. And be aware that document.write() is really bad way of displaying result.

Better ways are:

  • create/get div, span, p or some elem and use it like this: div.innerHTML = result;
  • console.log(result); // press F12 to open firebug/web tools

.

// map function that returns result:
function map(func, ary) {
    var i = 0;
    var result = [];   // empty array for results

    while(ary[i] != null){
        result[i] = func(ary[i]);
        i++;
    }
    return result;  // must return result
}

// objects {} and arrays[] are passed by reference to functions
function map(func, ary) {
    var i = 0;
    while(ary[i] != null){
        ary[i] = func(ary[i]);    // changing original `ary`
        i++;
    }
// no need to return anything  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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